文章程式碼顯示

2019年9月1日 星期日

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


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

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

int main()
{
    PTR_Student Amy = NULL;
    Amy = (PTR_Student)calloc(sizeof(Student),1);
    
    printf("[calloc]\r\n");
    printf("Before assign the init. value\r\n");
    printf("%d, %d \r\n", Amy->No, Amy->phone_number);
    
    Amy->No=1;
    Amy->phone_number=123;
    printf("After assign the init. value\r\n");
    printf("%d, %d \r\n", Amy->No, Amy->phone_number);

    free(Amy);

    return 0;
}



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

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

int main()
{
    PTR_Student Amy = NULL;
    Amy = (PTR_Student)malloc(sizeof(Student));
    
    printf("[malloc]\r\n");
    printf("Before assign the init. value\r\n");
    printf("%d, %d \r\n", Amy->No, Amy->phone_number);
    
    Amy->No=1;
    Amy->phone_number=123;
    printf("After assign the init. value\r\n");
    printf("%d, %d \r\n", Amy->No, Amy->phone_number);

    free(Amy);

    return 0;
}


補充 : 
原本預期 malloc 在 Before assign the initial value 前會取到 "不可預期的數值"
但可能是因為編譯器自動修正的關係所以取到的值亦為 0

但基於編譯器的不同可能導致不同的結果,我們還是必須知道 malloc 在配置記憶體後
其內部的值是不會自動設為 0 的


參考連結
malloc()和calloc()有啥区别


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


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

Blog 使用方針與索引