如果我想在主函数中声明一个动态大小的数组,我可以这样做:-
int m;
cin>>m;
int *arr= new int[m];
以下不能完成,因为编译器必须知道每个符号的大小,除非它是外部符号:-
int m;
cin>>m;
int arr[m];
我的问题是:
为什么编译器必须知道上面代码中arr的大小?它是符号表中未定义的局部符号。在运行时,堆栈会处理它(与 m 的方式相同)。是否因为编译器必须确定 main()(全局符号)的大小等于其中定义的所有对象的大小?
如果我有一个函数:
int func(int m)
我可以在函数内部定义 int arr[m] 还是我仍然必须这样做
int *a= new int[m]
最佳答案
例如:
int MyArray[5]; // correct
或
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
但是
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
这也是 C++ Programming Language, by Bjarne Stroustrup 中解释的内容:
The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a vector (§3.7.1, §16.3). For example:
关于c++ - 声明一个动态大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12336676/