Arsalan Sherwani
Arsalan Sherwani

Reputation: 560

How to assign vector size to array size c++?

How can I set the size of my array equal to the size of my vector. Here's my code:

vector<Point> data_obj;
int my_array[data_obj.size()]

but I get compile errors saying:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0

I am not understanding the error. Could you please provide some explanation?

Upvotes: 1

Views: 2740

Answers (3)

Marco Veglio
Marco Veglio

Reputation: 332

The matter is that arrays allocated through "classic" syntax (e.g. int a[5]) are allocated on stack. Therefore, you need to know at compile time how large the array is going to be, as the compiler needs to change the SP (stack pointer) value. On the other hand, vector's memory area is on the heap, like arrays allocated through malloc/new. Therefore you can wait till run time, to know how much memory you need and allocate it consequently.

Stack/vs heap allocation also has other pros/cons: stack allocation is way faster, since you just need to decrease a register value, but stack is limited in size and if your array is too large you'll end up with a Stack Overflow exception, which may lead to weird stuff happen like creating a wormhole dumping this entire site on your HDD :-) . Heap on the other hand is slower and too many allocation/deallocations may lead to fragment memory space.

Upvotes: -3

MateuszZawadzki
MateuszZawadzki

Reputation: 149

error C2057: expected constant expression

data_obj.size() is not constant when you allocate an array, but it should be - this is one of the requirements. If you want to do something like this, you need dynamic allocation.

error C2466: cannot allocate an array of constant size 0

in this case (when you didn't put anything to vector), its size is zero. You cannot create array with size 0.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117866

As the error says, the size of a static array must be constant at compile time. It is possible that the size of the std::vector may change during run time, so the size of the array is not guaranteed to be constant. You'd have to make a dynamic array

int* my_array = new int[data_obj.size()];

And remember to delete it after

delete[] my_array;

Upvotes: 5

Related Questions