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

reference to an array of size determined at run-time

本文关键字:数组 引用 运行时      更新时间:2023-10-16

我试图找到这个,但找不到任何。我知道我可以创建一个数组变量的引用:

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]'的值。有人知道怎么解决这个问题吗?

运行时长度数组是C99的一个特性,在标准c++中不存在。它们作为扩展出现在一些c++编译器上,但不能很好地与c++特性混合,比如引用和模板。

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