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

What is the difference between these two snippets of code?这两个代码片段有什么区别?

// 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;
}

and

// 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;
}

Is there something big I'm missing here?我在这里错过了什么大事吗? I'm thinking maybe face value wise these are the same but the underlying memory allocation is different?我想也许从面值上看,这些是相同的,但底层内存分配不同? I just can't grasp it.我就是无法掌握。

There are several differences here:这里有几个区别:

  • With malloc you can repeat the call multiple times, and get new valid memory area for your struct;使用 malloc,您可以多次重复调用,并为您的结构获取新的有效内存区域; there is only one statically allocated struct只有一个静态分配的结构
  • Memory obtained through malloc needs to be freed at the end;通过malloc获得的内存最后需要释放; statically allocated memory does not need freeing静态分配的内存不需要释放
  • Statically allocated struct is visible from multiple functions inside the translation unit;静态分配的结构在翻译单元内的多个函数中可见; memory from malloc is not shared with other functions unless you pass a pointer to them explicitly. malloc 中的内存不会与其他函数共享,除非您明确地将指针传递给它们。

In your first snippet pFile points to dynamically-allocated memory.在您的第一个片段中, pFile指向动态分配的内存。

In your second snippet, pFile points to a global variable.在您的第二个代码段中, pFile指向一个全局变量。

Other than the fact that you need to free the dynamic one yourself (which you haven't by the way), the way you interact with the struct is exactly the same in either case.除了您需要自己free动态对象这一事实(顺便说一下,您还没有free )之外,您与struct交互的方式在任何一种情况下都完全相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM