我的课本说数组是用const变量设置的.当我使用非const变量时,我可能会遇到哪些问题?

Jus*_*ker 1 c++ arrays

我正在阅读的C++书告诉我们,数组将使用常量变量设置,但我想让用户输入指示数组的大小,并且它有效.是否有我应该担心的问题.

riw*_*alk 5

你是怎么声明这个阵列的?

如果以这种方式声明,可以创建一个基于变量大小的数组:

int size;
cin >> size;
// (assert size is > 0 and < some really big number here)
int* myarray = new int[size];
// Do stuff with it here...
delete [] myarray;  // Don't forget this.
Run Code Online (Sandbox Code Playgroud)

这将工作得很好.您应该以这种方式创建数组:

int size;
cin >> size;
int myarray[size]; // should break with an ugly compiler error.
Run Code Online (Sandbox Code Playgroud)

如果你做了第二种方法并且它有效,那么你有一个奇怪的编译器,当你在其他平台上使用其他编译器时,你不应指望它工作.