文章程式碼顯示

2019年9月7日 星期六

《筆記》C語言 - 補充_11: 動態配置記憶體空間 calloc 與 malloc

這邊我以 calloc 舉例,並請注意到我 free 的對象

#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;
}





我的 Youtube 頻道,一定要訂閱
我將定期推出程式語言的新手教學影片


↓↓↓ 連結到部落格方針與索引 ↓↓↓

Blog 使用方針與索引