跳到主要内容

C 编程:动态在结构体中存储数据的程序

要理解这个示例,你应该具备以下 C编程 主题的知识:

这个程序要求用户输入 noOfRecords 的值,并使用 malloc() 函数动态地为 noOfRecords 结构体变量分配内存。

展示结构体的动态内存分配

#include <stdio.h>
#include <stdlib.h>
struct course {
int marks;
char subject[30];
};

int main() {
struct course *ptr;
int noOfRecords;
printf("请输入记录数:");
scanf("%d", &noOfRecords);

// 为 noOfRecords 结构体分配内存
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (int i = 0; i < noOfRecords; ++i) {
printf("请输入科目和成绩:\n");
scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
}

printf("展示信息:\n");
for (int i = 0; i < noOfRecords; ++i) {
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
}

free(ptr);

return 0;
}

输出

请输入记录数:2
请输入科目和成绩:
Science 82
请输入科目和成绩:
DSA 73

展示信息:
Science 82
DSA 73