Array of pointers and pointer to array in C ++

I have a class where it is protected section I need to declare an array with an unknown size (the size is specified by 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 just in the constructor I will use the "new" operator:

some_array_ = new int[size];

      

and it worked, my question is: can I declare an array in a class without specifying the size? and if so how to do it, if not then why does this work for pointers and not for normal array?

EDIT: I know vecotrs will solve the problem, but I cannot use them on my HW

+3


source to share


3 answers


You need to think about how this works from the compiler's point of view. The pointer uses a specific space (usually 4 bytes) and you are asking for more space with a new statement. But how much space does an empty array use? It cannot be 0 bytes, and the compiler does not know what space to allocate for an array without any elements, and therefore it is not allowed.



+1


source


You can always use a vector. To do this, add this line of code: #include <vector>

at the top of your code, and then define the vector like this:

vector<int> vectorName;



Keep in mind that vectors are not arrays and should not be treated as such. For example, in a loop, you would like to get a vector element like this vectorName.at(index)

and not like this:vectorName[index]

0


source


Suppose you have an integer array of size 2. So you have an array [0,1] Arrays are contiguous memery bytes, so if you declare one and then want to add one or more elements to the end of that array, then the next next position (in this case: at index 2 (or third integer)) has a high chance of being allocated already, so in this case you simply cannot do that. The solution is to create a new array (in this case, 3 elements), copy the original array to the new one and add a new integer in the last position. Obviously, this has a high cost, so we don't.

The solution to this problem in C ++ is Vector, and in Java, ArrayLists.

0


source







All Articles