文章程式碼顯示

2019年9月1日 星期日

《筆記》C語言 - 補充_7: struct 指標 搭配 calloc 配置記憶體空間


#include "stdio.h"
#include "stdlib.h"

typedef struct _Student{
    int No;
    int phone_number;
}Student, *PTR_Student;

int main()
{
    PTR_Student Amy = NULL;
    // calloc 會依 Student 這個 struct 的大小配置記憶體空間
    // 並且回傳該記憶體空間的起始位址(所以我們將這個位址強制轉型為 PTR_Student 並將這個位址儲存
    // 另外, calloc 在配置記憶體空間時會順便把這個空間內全部填滿 0 (而 malloc 不會填 0 )
    Amy = (PTR_Student)calloc(sizeof(Student),1); 
    
    Amy->No=1;
    Amy->phone_number=123;
    
    PTR_Student Tom = NULL;
    Tom = (PTR_Student)calloc(sizeof(Student),1);
    
    Tom->No=2;
    Tom->phone_number=789;
    
    printf("%d, %d \r\n", Amy->No, Amy->phone_number);
    printf("%d, %d \r\n", Tom->No, Tom->phone_number);

    free(Amy);
    free(Tom);
    
    return 0;
}




參考連結
malloc()、free()、calloc() 與 realloc()
malloc()和calloc()有啥区别


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


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

Blog 使用方針與索引