MST

星途 面试题库

面试题:C语言中malloc分配结构体数组内存的基础应用

假设有如下结构体定义:struct student { char name[20]; int age; }; 请编写代码,使用malloc为包含5个student结构体的数组分配内存,并对数组中的每个元素进行初始化,最后释放分配的内存。
13.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    // 使用malloc为包含5个student结构体的数组分配内存
    struct student {
        char name[20];
        int age;
    } *students = (struct student *)malloc(5 * sizeof(struct student));

    if (students == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    // 对数组中的每个元素进行初始化
    for (int i = 0; i < 5; i++) {
        snprintf(students[i].name, sizeof(students[i].name), "Student%d", i + 1);
        students[i].age = 18 + i;
    }

    // 输出初始化后的数据
    for (int i = 0; i < 5; i++) {
        printf("Name: %s, Age: %d\n", students[i].name, students[i].age);
    }

    // 释放分配的内存
    free(students);

    return 0;
}