c++ - 声明一个动态大小的数组

标签 c++ arrays compiler-construction

如果我想在主函数中声明一个动态大小的数组,我可以这样做:-

 int m;
 cin>>m;
 int *arr= new int[m];

以下不能完成,因为编译器必须知道每个符号的大小,除非它是外部符号:-

 int m;
 cin>>m;
 int arr[m];

我的问题是:

  1. 为什么编译器必须知道上面代码中arr的大小?它是符号表中未定义的局部符号。在运行时,堆栈会处理它(与 m 的方式相同)。是否因为编译器必须确定 main()(全局符号)的大小等于其中定义的所有对象的大小?

  2. 如果我有一个函数:

    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/

相关文章:

haskell - 解决极端情况 Haskell 模块导入和导出

c++ - Visual Studio C++ : When should I be using __declspec(dllimport)?

c++ - Qt-追加到QList

javascript - 迭代拼接多个数组

java - 如何在android中将HashMap转换为json数组?

cocoa - 综合属性和 ivar 错误

c++ - 使用 setprecision on 和 off

c++ - 用 g++ 编译 FLTK

php - 在数组中创建一个洞

algorithm - 程序员如何确保编译器创建正确的代码?