[英]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.