Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of pointers and pointer to an array in c++

i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:

int* some_array_;

and simply in the constructor i'll use the "new" operator:

some_array_ = new int[size];

and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?

EDIT: i know vecotrs will solve the problem but i can't use them on my HW

like image 561
Raeed mndow Avatar asked Jun 08 '26 16:06

Raeed mndow


1 Answers

You have to think about how this works from the compiler's perspective. A pointer uses a specific amount of space (usually 4 bytes) and you request more space with the new operator. But how much space does an empty array use? It can't be 0 bytes and the compiler has no way of knowing what space to allocate for an array without any elements and therefore it is not allowed.

like image 187
Tetrahedron Avatar answered Jun 11 '26 06:06

Tetrahedron