开发者

C++ array Visual Studio 2010 vs Bloodshed Dev-C++ 4.9.9.2

This code compiles fine in Bloodshed Dev开发者_Python百科-C++ 4.9.9.2, but in Visual Studio 2010 I get an error: expression must have a constant value. How do I make an array after the user input about array size without using pointers?

#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
    int size = 1;
    cout << "Input array size ";
    cin >> size;
    int array1[size];
    system("PAUSE");
    return 0;
}


Use an std::vector instead of an array (usually a good idea anyway):

std::vector<int> array1(size);

In case you care, the difference you're seeing isn't from Dev-C++ itself, it's from gcc/g++. What you're using is a non-standard extension to C++ that g++ happens to implement, but VC++ doesn't.


The ability to size automatic arrays using a variable is part of C, not part of C++, and is an extension that GCC seems to want to foist on us all. And DevC++ is an unholy piece of cr*p, although it is not at fault here. for a change (this is entirely GCC's doing) - I can't imagine why you (or anyone else) would want to use it.

You should really compile your C++ code with GCC with flags that warn you about stuff like this. I suggest -Wall and -pedantic as a minimum.


Or

int array1 = new int[size];

will work aswell I believe (been a month or 3 since I last touched C++)

But indeed, if using C++, go for an std::vector, much more flexible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜