【问题标题】:C++ arrays with user input size (aka Why does this compile?)具有用户输入大小的 C++ 数组(又名为什么会编译?)
【发布时间】:2021-04-02 15:33:44
【问题描述】:

我在 win 10 上使用 clang (10.0) 进行实验,使用以下 sn-p:

#include <iostream>

using namespace std;

int main()
{
  const int N = 10;

  int ii;
  cout << "Enter value for ii: ";
  cin >> ii;

  int a[N+ii];

  for (int i = 0; i < N+ii; ++i) {
    a[i] = 0;
  }

  for (int i = 0; i < N+ii; ++i) {
    cout << "a[ " << i << "] = " << a[i] << endl;
  }

  return 0;
}

我不确定为什么没有编译错误(数组a的大小在编译时是未知的)????

PS:

  1. 两个for 循环都是为了触发分段错误。
  2. 编译命令:clang.exe exp.cpp
  3. 我尝试使用较大的 ii 值运行代码,但它似乎工作正常(ii = 10000、100000、1000000)

【问题讨论】:

标签: arrays memory-leaks clang dynamic-memory-allocation


【解决方案1】:

int a[N+ii];

这在 C++ 中是不正确的。数组变量的大小必须是编译时常量。

我不确定为什么没有编译错误(数组a的大小在编译时是未知的)????

C++ 标准要求不能编译格式错误的程序。当编译器有意编译格式错误的程序时,您使用的是语言扩展。

该标准确实要求语言实现发出诊断消息,告知用户其格式错误的程序。除非您在编译时提供 -pedantic 选项,否则 Clang 不符合标准。如果您确实使用它,这就是 clang 所说的:

warning: variable length arrays are a C99 feature [-Wvla-extension]

这就是 clang 文档中关于该选项的内容:

-pedantic, --pedantic, -no-pedantic, --no-pedantic

语言扩展警告

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多