數據結構復習之C語言malloc()動態分配內存概述


#include <stdio.h>
#include <malloc.h>

int main(void)
{
    int a[5] = {4, 10, 2, 8, 6};
    // 計算數組元素個數
    int len = sizeof(a)/sizeof(a[0]);
    int i;

    //printf("%d", len);

    // sizeof(int) int類型的字節數
    // 動態分配內存
    // malloc返回第一個字節的地址
    int *pArr = (int *)malloc(sizeof(int) * len);

    for(i = 0; i < len;i++)
        scanf("%d", &pArr[i]);

    for(i = 0; i < len;i++)
        printf("%d\n", *(pArr + i));

    free(pArr); // 把pArr所代表的動態分配的20個字節的內存釋放

    return 0;
}

 

跨函數使用內存
函數內的局部變量,函數被調用完之后,變量內存就沒有了。
如果是一個動態的變量,動態分配的內存必須通過free()進行釋放,不然只有整個程序徹底結束的時候
才會釋放。
跨函數使用內存實例:

#include <stdio.h>
#include <malloc.h>

struct Student
{
    int sid;
    int age;
};

struct Student *CreateStudent(void);

int main(void)
{
    struct Student *ps;

    ps = CreateStudent();
    ShowStudent(ps); // 輸出函數

    return 0;
}

struct Student *CreateStudent(void)
{
    // sizeof(struct Student) 結構體定義的數據類型所占用的字節數
    struct Student *p = (struct Student *)malloc(sizeof(struct Student)); // 創建
    // 賦值
    p->sid = 99;
    p->age = 88;
    return p;
};

void ShowStudent(struct Student *pst)
{
    printf("%d %d\n", pst->sid, pst->age);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM