【问题标题】:length of array at runtime in C++ [duplicate]C ++中运行时数组的长度[重复]
【发布时间】:2014-12-08 05:38:30
【问题描述】:

我被要求证明可以在程序中设置数组长度,并且不需要在编译时确定。我有以下代码:

#include<iostream>
using namespace std;
int main()
{
    int x, myarray[x];
    cout << "Enter the size of array" << endl;
    cin >> x;
        }

但是当我编译时,我得到以下错误:

error C2057: expected constant expression
 error C2466: cannot allocate an array of constant size 0
 error C2133: 'myarray' : unknown size

我不确定处理它的正确方法。

【问题讨论】:

  • 你无法证明这一点,因为数组大小必须是编译时常量。
  • x 实际上包含什么,当你说 myarray[x]?!?
  • int x, myarray[x]; 即使 C++ 有可变长度数组。你确实意识到 x 没有在这里初始化..

标签: c++ runtime variable-length-array


【解决方案1】:

整数矩阵[x]; 我不认为 c++ 不支持这种声明。如果要为数组动态分配内存,请使用 new[] 运算符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多