在此示例中,您將學(xué)習(xí)存儲(chǔ)用戶使用動(dòng)態(tài)內(nèi)存分配輸入的信息。
要理解此示例,您應(yīng)該了解以下C語(yǔ)言編程主題:
這個(gè)程序要求用戶存儲(chǔ)noOfRecords的值,并使用malloc()函數(shù)動(dòng)態(tài)地為noOfRecords結(jié)構(gòu)變量分配內(nèi)存。
#include <stdio.h>
#include <stdlib.h>
struct course {
int marks;
char subject[30];
};
int main() {
struct course *ptr;
int i, noOfRecords;
printf("輸入記錄數(shù): ");
scanf("%d", &noOfRecords);
//noOfRecords結(jié)構(gòu)的內(nèi)存分配
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (i = 0; i < noOfRecords; ++i) {
printf("分別輸入主題和標(biāo)記的名稱:\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;
}輸出結(jié)果
輸入記錄數(shù): 2 分別輸入主題和標(biāo)記的名稱: Programming 22 分別輸入主題和標(biāo)記的名稱: Structure 33 顯示信息: Programming 22 Structure 33