difference when defining array under Linux or Windows
Here is a simple code of defining an array. I noticed this code will work(compile and run) under Linux(OpenSue,gcc compiler), but it will not work under W开发者_开发问答indows system. The compiler gave error prompt. Does anybody know the reason? Thanks!
#include <iostream>
using namespace std;
int main()
{
int N;
cin>>N;
int ar[N];
ar[0]=0;
cout<<"ar[0]= "<<ar[0]<<endl;
return 0;
}
The code isn’t valid C++ since C++ does not allow declaring a (stack-allocated) array with a variable size as you do. The reason for this is that C++ offers better mechanisms of declaring dynamically sized arrays, using the std::vector
class from its standard library:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int N;
cin >> N;
vector<int> ar(N);
ar[0] = 0;
cout << "ar[0] = " << ar[0] << endl;
return 0;
}
g++
(the compiler you used on Linux) by default allows this through a compiler extension.
This isn't really a difference between Linux and Windows per se. It's a difference between gcc and MS VC++.
This type of code is legal and allowed in C (as of C99). It's not, however, allowed in C++ -- but gcc provides it as an extension in C++ anyway. In this particular respect, MS VC++ attempts to follow the (C++) standard more closely, and does not provide this particular extension.
If you run gcc on Windows, however, (e.g., Cygwin or MinGW) you'll get the same behavior on Windows that you're currently observing on Linux.
As @Konrad Rudolph already pointed out, the right way to handle this under C++ is almost certainly to switch from using an array to using a vector instead.
Variable-length arrays (e.g. int ar[N];
) are not permitted in C++, but GCC can do them anyway.
not sure why it compiles in linux, but you can't declare int ar[N] on the stack like that.
精彩评论