Raeed mndow
Raeed mndow

Reputation: 75

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

Upvotes: 3

Views: 177

Answers (3)

DIMITRIOS
DIMITRIOS

Reputation: 305

Lets say that you have an integer array of size 2. So you have Array[0,1] Arrays are continuous byte of memery, so if you declare one and then you want to add one or more elements to end of that array, the exact next position (in this case :at index 2(or the 3rd integer) ) has a high chance of being already allocated so in that case you just cant do it. A solution is to create a new array (in this case of 3 elements) , copy the initial array into the new and in the last position add the new integer. Obviously this has a high cost so we dont do it.

A solution to this problem in C++ is Vector and in Java are ArrayLists.

Upvotes: 0

Tetrahedron
Tetrahedron

Reputation: 11

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.

Upvotes: 1

Ken
Ken

Reputation: 569

You could 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 as follows:

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 want to retrieve an element of a vector like this: vectorName.at(index) and not like this: vectorName[index]

Upvotes: 0

Related Questions