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

May 12, 2012 at 1:27am
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 May 12, 2012 at 1:44am
May 12, 2012 at 3:40am
> 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 May 12, 2012 at 3:45am
May 12, 2012 at 4:32am
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.
May 12, 2012 at 9:22pm
closed account (4z0M4iN6)
I suggest, you should write:

Mail * mailPtr = new Mail[filenum];

and later you shouldn't forget: delete mailPtr;
May 13, 2012 at 7:04am
Also, don't forget that an array allocated with  new array[]  should be de-allocated with  delete [] array.

Topic archived. No new replies allowed.