简体   繁体   English

这个C ++代码是如何在GCC中运行而不是在Visual C ++中运行的?

[英]How is this C++ code running in GCC but not Visual C++?

#include<iostream>
using namespace std;
main()
{
  int m;
  cin>>m;
  int re[m];
  cout<<sizeof(re);
} 

This code is running perfectly in codeforces GNU C++ 4.7(But not in my Microsoft Visual C++). 这段代码在代码GNU C ++ 4.7中运行得很好(但不是在我的Microsoft Visual C ++中)。 But why? 但为什么? shouldn't the array size be a constant? 数组大小不应该是常数吗?

As you mentioned, C++ array sizes must be constant expressions. 如前所述,C ++数组大小必须是常量表达式。
- With VS, you will get: error C2057: expected constant expression - 使用VS,您将得到: error C2057: expected constant expression
- GCC has an extension to the standard, which allows your code to compile. - GCC具有标准的扩展,允许您的代码进行编译。

Variable length arrays are introduced in C99. 可变长度数组在C99中引入。 Standard C++ doesn't support it, but GCC supports it as an extension: 标准C ++不支持它,但GCC支持它作为扩展:

See GCC extension: Arrays of Variable Length for detail. 有关详细信息,请参阅GCC扩展:可变长度数组

For stack allocation, array size needs to be determined at compile time. 对于堆栈分配,需要在编译时确定数组大小。 But the array size is determined at runtime, so it must go on the heap. 但是数组大小是在运行时确定的,因此它必须在堆上。

Use 采用

int *re = new int[m];
cout << m << endl;
delete[] re;

As others already mentioned, your code is non-standard C++ as you have a variable length array : 正如其他人已经提到的,你的代码是非标准的C ++,因为你有一个可变长度的数组

  int m;
  cin>>m;
  int re[m]; // m is not a compile time constant!

GCC allows this as language extension . GCC允许这作为语言扩展 You get a warning if you enable -Wvla . 如果启用-Wvla收到警告。 Afaik, this code gets rejected if you enfore gcc to use a specific c++ standard, such aus -std=c++11 . Afaik,如果你想让gcc使用特定的c ++标准,例如aus -std=c++11 ,那么这段代码就会被拒绝。

Now you _could do this instead (as Paul Draper already wrote) 现在你可以这样做(正如Paul Draper已经写过的那样)

int *re = new int[m]; // dynamic array allocation
delete[] re;          // giving the memory back to the operating system

However, C++ provides an easy to use wrapper for this: 但是,C ++提供了一个易于使用的包装器:

std::vector<int> re(m);

For most things, vector behaves just like a dynamically allocated array, but prevents you from accidentally forgetting to delete or double delete and makes passing the data to functions a bit easier. 对于大多数情况,vector的行为就像一个动态分配的数组,但可以防止您意外忘记delete或双重delete ,并使数据更容易传递给函数。 Learn more about vector on cppreference.com . cppreference.com上了解有关矢量的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM