这两段代码有什么区别?
// 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 的内存不会与其他函数共享,除非您明确地将指针传递给它们。
关于c - 使用 malloc 将内存分配给结构指针和将结构指针指向结构的内存地址有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40041706/