簡體   English   中英

使用 malloc 為結構指針分配內存和將結構指針指向結構的內存地址有什么區別?

[英]What is the difference between using malloc to allocate memory to a struct pointer and pointing a struct pointer to a struct's memory address?

這兩個代碼片段有什么區別?

// Structure
struct file {
    int fileSize;
};

int main(void) {
    // Variables
    struct file *pFile = (struct file*) malloc(sizeof(struct file)); // Declare pointer of type struct file and allocate enough room

    pFile->fileSize = 5;

    free(pFile);

    return 0;
}

// Structure
struct file {
    int fileSize;
} file1;

int main(void) {
    // Variables
    struct file *pFile = &file1; // Declare pointer of type struct file and point to file1 struct

    pFile->fileSize = 5;

    return 0;
}

我在這里錯過了什么大事嗎? 我想也許從面值上看,這些是相同的,但底層內存分配不同? 我就是無法掌握。

這里有幾個區別:

  • 使用 malloc,您可以多次重復調用,並為您的結構獲取新的有效內存區域; 只有一個靜態分配的結構
  • 通過malloc獲得的內存最后需要釋放; 靜態分配的內存不需要釋放
  • 靜態分配的結構在翻譯單元內的多個函數中可見; malloc 中的內存不會與其他函數共享,除非您明確地將指針傳遞給它們。

在您的第一個片段中, pFile指向動態分配的內存。

在您的第二個代碼段中, pFile指向一個全局變量。

除了您需要自己free動態對象這一事實(順便說一下,您還沒有free )之外,您與struct交互的方式在任何一種情況下都完全相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM