在 C++ 中是否允许创建具有运行时边界的数组?

Is creating arrays with runtime bounds allowed in c++?

根据 在 C++ 中不允许创建具有运行时边界的数组。

但是我得到了下面的代码编译没有错误。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {


    int n;
    cin>>n;

    int a[n][n];
    a[n-1][n-1]=9;
    cout<<a[n-1][n-1]<<endl;

    return 0;
}

而且效果也很好。在这里检查 -> http://cpp.sh/6bies

有人可以帮助解决这个困惑吗?

如果您使用的是 gcc,它有一些扩展,其中之一是支持 C99 中可用的可变长度数组 (VLA)。

Is creating arrays with runtime bounds allowed in c++?

这样的数组格式不正确。

But I get below code compiled without errors. ... and it works fine too.

C++ 标准不允许编译器成功编译格式错误的程序。显示诊断消息就足够了。这允许编译器扩展语言。

如果您查看示例的编译器输出,您会发现编译器确实告诉了您相关信息,这是 C++ 标准所要求的:

15:15: warning: array of array of runtime bound [-Wvla]

因此,您的编译器似乎支持运行时绑定数组 - 甚至运行时绑定数组的数组 - 作为语言扩展。

如果您愿意,可以要求大多数编译器拒绝根据 C++ 标准格式错误的程序。


在动态存储中创建运行时绑定数组符合标准。最简单的方法是使用 std::vector.