可能重复:
数组名称是 C 中的指针吗?
C++ 静态数组与动态数组?
我正在学习 C,但我对以下两个数组之间的区别感到困惑:
int a[10];
和
int *b = (int *) malloc(10 * sizeof(int));
只是在最基本的层面上,这两者有什么区别?
可能重复:
数组名称是 C 中的指针吗?
C++ 静态数组与动态数组?
我正在学习 C,但我对以下两个数组之间的区别感到困惑:
int a[10];
和
int *b = (int *) malloc(10 * sizeof(int));
只是在最基本的层面上,这两者有什么区别?
int a[10];
在堆栈上分配,并在作用域结束后立即解除分配。
int *b = (int *) malloc(10 * sizeof(int));
分配在堆上并且在程序的整个生命周期中都是活动的,除非它是明确释放的。
一旦您离开当前堆栈帧(基本上,当您所在的函数返回时),静态数组就会被销毁。动态数组会一直存在,直到你 free() 它。
The first lives on the stack (= lives as long as the scope of the variable), the second lives on the heap (= lives until freed). The first has a fixed size, whereas the second can be re-sized.