我正在努力学习 malloc()/free() 的 C 语言规则。考虑下面的代码,它运行得很好。 (在 Linux 上,使用 GCC 编译。)具体来说,我想知道 arr
数组。我知道你必须为数组内的所有结构元素分配内存...但你为什么不必为数组分配内存 本身?
#include<stdio.h>
#include<stdlib.h>
#define ARR_SIZE 100
typedef struct containerStruct{
int data1;
int data2;
int data3;
// ...etc...
} container;
int main(){
container* arr[ARR_SIZE]; // Don't I have to malloc this?
int i;
for(i=0; i<ARR_SIZE; i++){
arr[i] = (container*) malloc (sizeof(container)); // I get why I have to malloc() here
}
...do stuff...
for(i=0; i<ARR_SIZE; i++){
free(arr[i]); // I get why I have to free() here
}
// Don't I have to free(arr) ?
return 0;
}
我猜 container* arr[ARR_SIZE];
行告诉编译器它需要知道的所有信息,以便在内存中为数组开辟空间,这就是这段代码起作用的原因。
但不知何故,它仍然“感觉”不对。当我 malloc() 某些东西时,我在堆上保留内存空间,对吗?但是我的 container* arr[ARR_SIZE];
调用在堆栈上创建了数组。所以......容器*搬运工数组存在于堆栈中,所有这些容器*指针都指向堆上的容器结构。对吗?
最佳答案
在 arr
声明的正下方,您有以下内容:
int i;
它保留了足够的空间(可能在“堆栈”上) 来存储int
。您是否也“感觉”不对?
arr
的声明没有什么不同。编译器为 container *
的 ARR_SIZE
元素数组分配足够的空间(可能在“堆栈”上)。
关于c - 我不需要 malloc() 这个数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635071/