How to define an array with an arbitrary size! Reading the size of array from a file?

I'm trying to declare an array with size of non-constant. g++ compiler was ok but CC compiler asked me to define a constant one. Here is an abstract of code:


1
2
3
4
	getline(fin,tmp);
	      int filenum = atoi(tmp.c_str());

	Mail* mailPtr[filenum];


The error is:

Error: An integer constant expression is required within the array subscript operator.
Last edited on
> g++ compiler was ok

g++ compiler was not ok.

g++ is not a conforming C++ compiler unless one of the options --std=c++11 or --std=c++0x is used.
Or for obsolete C++ either --std=c++98 or --ansi.

1
2
3
4
5
6
7
	getline(fin,tmp);

	int filenum = atoi(tmp.c_str()); 
        // atoi() may fail; you need to add a check here

	// Mail* mailPtr[filenum];
        std::vector<Mail*> mailPtr(filenum) ;
Last edited on
To be specific, non-constant size arrays only exist in C. Some compilers, such as g++, allow this C-only feature in C++ programs. Here's is where it's mentioned in the GCC documentation: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html#Variable-Length

C++ has vectors, as already mentioned.
closed account (4z0M4iN6)
I suggest, you should write:

Mail * mailPtr = new Mail[filenum];

and later you shouldn't forget: delete mailPtr;
Also, don't forget that an array allocated with  new array[]  should be de-allocated with  delete [] array.

Topic archived. No new replies allowed.