#include "stdio.h"
#include "stdlib.h"
#define numberStudent 10
typedef struct _Student{
int No;
int score;
}Student, *PTR_Student;
int main()
{
PTR_Student studentTemp = NULL;
studentTemp = (PTR_Student)calloc(sizeof(Student)*numberStudent, 1);
if (studentTemp == NULL){ /* 檢查是否成功配置記憶體空間 */
printf("Allocate the memory fail.");
return -1;
}
else { printf("Allocate the memory success.\r\n"); }
int* memoryBeginAddr = studentTemp;/* 儲存calloc回傳的起始位址,隨意用一個一般的指標變數儲存即可 */
for (int i = 1; i <= numberStudent; i++){
studentTemp->No = i;
studentTemp->score = i*10;
studentTemp++;
}
studentTemp = memoryBeginAddr;
for (int i = 1; i <= numberStudent; i++){
printf("student No. %d, score : %d\r\n", studentTemp->No, studentTemp->score);
studentTemp++;
}
//free(studentTemp); /* 注意 free 的對象應該要是當初 malloc 回傳的位址*/
free(memoryBeginAddr);
return 0;
}
我將定期推出程式語言的新手教學影片