代码之家  ›  专栏  ›  技术社区  ›  LiamJM

二维数组-表达式必须具有常数值错误

  •  0
  • LiamJM  · 技术社区  · 7 年前

    我正在尝试 Latin Square Daily Challenge on Reddit 我想使用一个数组,通过使用以下代码在运行时分配大小:

    int n;
    cout << "Please enter the size of the Latin Square: ";
    cin >> n;
    int latinsquare[n][n];
    

    这在联机编译器中有效,但在Visual Studio 17中无效。有没有办法在Microsoft C++编译器中实现这一点?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sergey Kalinichenko    7 年前

    why? ). 您可以分配 latinsquare new ,但在C++中,一种惯用的方法是使用向量的向量:

    std::vector<std::vector<int>> latinsquare(n, std::vector<int>(n, 0));
    
        2
  •  1
  •   kocica    7 年前

    VLA 标准如果你想使用它们,你需要编译器扩展。

    • 通过动态创建 new delete 操作员

    • std::vector