【问题标题】:Array of non-constant size: Why does this even work? [duplicate]非常量大小的数组:为什么这甚至可以工作? [复制]
【发布时间】:2014-04-12 07:28:46
【问题描述】:
#include <iostream>
using namespace std;

int main(){
    int n;
    cout<<"Enter the size :";
    cin>>n;
    int array[n];  // I've worked some outputs and it works 
    return 0;
}

这是某种动态分配吗?
为什么它甚至没有给出一个错误,因为 'n' 是一个“const”?

另外,写入cout &lt;&lt; array[n+5]; 不会导致编译时或运行时错误。

我正在使用 Dev-C++。

【问题讨论】:

  • +1 不是问为什么它不起作用,而是为什么它不应该起作用。
  • 它不是动态的。 nints 在堆栈上分配,它们在作用域结束时被释放。标准不支持它,但 g++ 允许它作为扩展。另请注意,它在 C99 中是允许的。
  • 嗯,这不是标准的编码方式,但是很难想出一个编译器语法来故意让它不起作用:P
  • @NiklasB。它适用于-std=c++11。要禁用 GNU 扩展,必须使用 -pedantic 或更好的 -pedantic-errors
  • @Drop 很高兴知道,谢谢

标签: c++ arrays memory dynamic compiler-errors


【解决方案1】:

显然可以在 C99 中声明变长数组,而且好像是GCC accepts then for C++ also

在 ISO C99 中允许使用可变长度自动数组,并作为 扩展 GCC 在 C90 模式和 C++ 中接受它们。这些数组是 像任何其他自动数组一样声明,但长度为 不是常量表达式。

你每天都会学到一些东西......我以前没见过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多