在此示例中,您将学习存储用户使用动态内存分配输入的信息。
要理解此示例,您应该了解以下C语言编程主题:
这个程序要求用户存储noOfRecords的值,并使用malloc()函数动态地为noOfRecords结构变量分配内存。
#include <stdio.h>
#include <stdlib.h>
struct course {
int marks;
char subject[30];
};
int main() {
struct course *ptr;
int i, noOfRecords;
printf("输入记录数: ");
scanf("%d", &noOfRecords);
//noOfRecords结构的内存分配
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (i = 0; i < noOfRecords; ++i) {
printf("分别输入主题和标记的名称:\n");
scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
}
printf("显示信息:\n");
for (i = 0; i < noOfRecords; ++i)
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
return 0;
}
输出结果
输入记录数: 2
分别输入主题和标记的名称:
Programming
22
分别输入主题和标记的名称:
Structure
33
显示信息:
Programming 22
Structure 33