【问题标题】:array + constant expression in c++ [closed]C ++中的数组+常量表达式[关闭]
【发布时间】:2018-04-23 10:47:44
【问题描述】:

我想从用户那里获取 n 并将其放在数组表达式中,但在 Visual Studio 2017 中出现错误(表达式必须具有常量值),我看到其他编译器可以完美地使用它。 我以为我可以使用 new 或指针,但这些也不起作用。 我知道它有类似的主题(我无法理解它们并将它们与我的问题相匹配)但如果有人为我编写正确的代码会很棒。 谢谢。

  int n;
    cout <<"Enter n:" ;
    cin >> n;
    int a[n];    //recive error for n (expression must have a constant value)

    for(int i=0;i<n;i++)
         a[i]=rand() % 100;

    for(int i=0;i<n;i++)        
        cout<<setw(5)<< a[i];

【问题讨论】:

  • “但如果有人为我写正确的代码就好了” - std::vector&lt;int&gt; a(n);
  • @StoryTeller...std::vector&lt;int&gt; a(n);.
  • “我认为我可以使用 new 或指针,但它们也不起作用。” - 你为此尝试了什么代码?
  • @sgarizvi - 那些令人讨厌的页面及其刷新率;)

标签: c++ arrays constants


【解决方案1】:

在 C++ 中,数组必须具有固定大小。您不能拥有一个大小取决于运行时值的普通数组。这就是编译器抱怨nint a[n]; 中不是常量的原因。

您应该改用std::vectorstd::vector&lt;int&gt; a(n); 将创建一个可以容纳n 元素的向量。您的其余代码可以保持不变。

【讨论】:

  • 感谢快速重播。像魅力一样工作。
【解决方案2】:

“我认为我可以使用 new 或指针,但它们也不起作用。”...你真的这样做了吗?

第一个解决方案是一些答案建议您可以使用向量。

但是,如果您想使用指针和 new(这是唯一的方法,因为数组声明需要在声明时使用常量大小),您可以使用以下内容:

int n;
cout <<"Enter n:" ;
cin >> n;
int *a;    //recive error for n (expression must have a constant value)
a = new int [n];  // <--- this will allocate the memory to create an array of size n.

for(int i=0;i<n;i++)
     a[i]=rand() % 100;

for(int i=0;i<n;i++)        
    cout<<setw(5)<< a[i];

记得在新建后使用删除。 (删除 [] a);

【讨论】:

  • 感谢您展示了我必须如何正确使用 pinter 和 new,这对我很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多