#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
return 0;
}
数组的大小由用户在运行时输入,但内存是在堆栈上分配的。这是什么类型的内存分配?静态还是动态?
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
return 0;
}
数组的大小由用户在运行时输入,但内存是在堆栈上分配的。这是什么类型的内存分配?静态还是动态?
与 C++ 中的可变长度数组相关联的所有保留,这是一个它是堆栈中的动态分配
int * arr = new arr[n];
这取决于编译器。相关的问题是因为在编译时大小是未知的,一些其他局部变量在堆栈中的偏移量也不能静态知道例如使用 g++ :
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
int other;
cout << &n << ' ' << arr << ' ' << &other << ' ' << new int[n] << endl;
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
10
0xbe9d825c 0xbe9d8230 0xbe9d8258 0xd84868
pi@raspberrypi:/tmp $
可见arr被放置在n和other之间的堆栈中,堆位于内存中的其他位置
即使像 g++ 这样的编译器允许变长数组,也不建议使用它们,因为:
这是静态内存分配,但在静态内存分配中,您不能从用户那里获取大小。为了从用户那里获取大小,您必须进行动态内存分配。