在运行时确定大小的数组引用

4

我尝试寻找,但没有找到。我知道我可以创建一个数组变量的引用:

int x[10] = {}; int (&y)[10] = x;

然而,如果数组大小在编译时未知,就像以下代码中一样:
const int n = atoi( string ); //the string is read from a text file at run time.
int x[n] = {}; int (&y)[n] = x; //this generates a compiling error.

即使int n被声明为const,只要n在编译时不确定,引用就无效。编译器会报错,类似于:类型'int [n]'的引用不能绑定到不相关类型'int [n]'的值上。有人知道如何解决吗?提前感谢。
2个回答

6

运行时长度数组是C99的特性,在标准的C++中并不存在。它们在某些C++编译器上作为扩展存在,但与C++特性(如引用和模板)不兼容。

你应该使用vector。


0
在C++中不应该使用动态声明数组的特性,因为并非所有编译器都支持它。考虑使用STL容器,例如std::vector<int>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接