[英]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:这里有几个区别:
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.