以下两种在 C 语言中创建数组的方法是否等效?
int main( void )
{
int *array = malloc(sizeof(int) * 10);
int array2[10];
}
我的想法是方法二是方法一的语法糖,但我不确定。
此外,在这些声明之后,array 和 array2 包含什么?我知道数组是指向数组开头的指针,但是数组初始化为什么?对于 array2 怎么样?
最佳答案
它们根本不是等价的。这:
int *array = malloc(sizeof(int) * 10);
将分配堆的一 block 内存,并留下一个指向该内存的指针。
这个:
int array2[10];
将在堆栈上分配一些内存。阅读关于堆栈和堆内存的优秀答案:What and where are the stack and heap?
关于c - C 中的数组创建语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050789/