Array

Hi,

Trying to do something simple here but getting an annoying error - constant expression required - how do I get round this?


1
2
3
4
5
6
7
8
9
10

int main()
{
  long array[];
  
  GetSize(&size);
  
  long array[size];
}


Thanks
If you had read the chapter on arrays in c++ - you would have been aware that array subscripts
have to be a constant value - For example:

1
2
3
const int size = 50;
int arr[23]; 
long numRows[size];


Last edited on
C++ does not do variable length arrays on the stack. C does since C99.

It was considered being put into C++ for C++0x, but was not. There is a big discussion all about it here:

http://groups.google.com/group/comp.std.c++/browse%5Fthread/thread/2bfe25800d4961e8/9545494bbb336dfa

To my mind, the best reason for not having it in C++ is because we have better ways of doing it already, unless you simply must have a naked array, when you can make it anyway on the heap.

Try this, for example, instead of long array[size];:

vector<double> array(size);
Thanks for the replies but the solution I was looking for was,

1
2
3
4
5
6
7
8
9
10
11
12

int main()
{
  long array[];
  
  GetSize(&size);
  
  long* array = new long[size];

  if(array != NULL) delete array;
}


puts the array on the Heap instead,

Thanks
Moschops wrote:
you can make it anyway on the heap.


You're welcome.
In C++, you don't need to do that
1
2
3
4
5
6
7
8
9
10
int main()
{
  long array[];
  
  GetSize(&size);
  
  long* array = new long[size];

  if(array != NULL) delete array;
}

just use vector instead of handcrafting array
besides, you cannot write something like
 
long array[]

you must tell the compiler how many space do you need before the run time
instead, you should
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  
  GetSize(&size);
  
int *array = 0;
  try
  {
    array = new int[size];
  }
  catch(std::bad_alloc &memAllExcept)
  {
    std::cerr<<memAllExcept.what()<<"\n";
  }

  delete []array;

use try & catch to handle the possible errors of memory allocation
 
puts the array on the Heap instead

vector would put the "array" on the heap, same like the handcrafting code
but it is safer and easier to use than handcrafting array like above
Last edited on
Topic archived. No new replies allowed.