[英]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;
}
我在这里错过了什么大事吗? 我想也许从面值上看,这些是相同的,但底层内存分配不同? 我就是无法掌握。
这里有几个区别:
在您的第一个片段中, pFile
指向动态分配的内存。
在您的第二个代码段中, pFile
指向一个全局变量。
除了您需要自己free
动态对象这一事实(顺便说一下,您还没有free
)之外,您与struct
交互的方式在任何一种情况下都完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.