繁体   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