原文: https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation
要理解此示例,您应该了解以下 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("Enter the number of records: ");
scanf("%d", &noOfRecords);
// Memory allocation for noOfRecords structures
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (i = 0; i < noOfRecords; ++i) {
printf("Enter the name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr + i)->subject, &(ptr + i)->marks);
}
printf("Displaying Information:\n");
for (i = 0; i < noOfRecords; ++i)
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
return 0;
}
输出
Enter the number of records: 2
Enter the name of the subject and marks respectively:
Programming
22
Enter the name of the subject and marks respectively:
Structure
33
Displaying Information:
Programming 22
Structure 33