when I initialize the array in this way:

const int size = 10;
int myArray;

it works well. But I have to initialize it in this way:

const int size =pow(2, Depth()+1)-1;
int myArray;

in this case it throw an error which is "expected constant expression"

What should I do??? :sad:

11 Years
Discussion Span
Last Post by John A

An array size has to be a compile time constant. const int size = 10; is a compile time constant because the value you initialize it with, 10, is also a compile time constant. const int size =pow(2, Depth()+1)-1; is not because the result of pow() and Depth() aren't known until run time.

This is where you use a dynamic array.

const int size =pow(2, Depth()+1)-1;
int *myArray = new int[size];

Or better yet, a vector. :)

#include <vector>

const int size =pow(2, Depth()+1)-1;
std::vector<int> v(size);

Thanks Ravalon I prefer the dynamic one :)


Vectors are better in almost ever respect - to change the size of a dynamic array, you must first delete the entire structure and then reallocate one of a different size.

Vectors on the other hand can add and remove items as needed, and there's little if no speed hit taken when using them. Furthermore, you can use them like arrays if you want:

std::vector<int> MyArray(size);
MyArray[0] = somerandomvalue;

And you can't beat being able to delete an element in the middle of a list without leaving a gap. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.