Reputation:
Could someone please explain what each line is really doing here. I know overall it allocates 4 spaces, but I don't understand the details.
int** arrayArray;
arrayArray= new int*[4];
for (int x = 0; x < 4; ++x)
{ arrayArray[x] = new int[4];}
Upvotes: 2
Views: 93
Reputation: 2012
Your array is a 2D array, so it size is in forms of "x by y". The total int
s your array contains will be x*y. I will call x as the row number and y as the column number.
It seems like you need a array with total 4 int
s, so your row number and column number should have a product of 4, for example 2x2. Keep in mind that the following answer is dealing with a 4x4 array, which has 16 total int
s.
Allocation:
int** arrayArray;
This line decelar a variable arrayArray
, which is a pointer of ( pointer of int
). Like
(arrayArray) -> * -> int
So arrayArray[0]
gives you a pointer of int
, and arrayArray[0][0]
therefore give you an int
(which is in the array).
arrayArray = new int*[4];
This line allocate a space that can contain 4 pointers of int
, and set the arrayArray
to point to that space (don't forget that arrayArray
is a pointer of a pointer of int
. ).
Here the 4
means row number.
for (int x = 0; x < 4; ++x)
arrayArray[x] = new int[4];
For every pointer in arrayArray
, set it to point to a space for 4 int
s.
Here the 4 in new int[4]
means column number.
So the structure of this array will be something like
Deallocation (free
):
Notice that arrayArray
by it self is just a pointer to 4 other pointer. If you want to free the entire array, you don't just free the space for the 4 pointers. You need to free every space these pointer points to, else you will cause memory leak. For example you want to free the entire array, it is just the reverse of allocation, first free all the space arrayArray
points to:
for (int x = 0; x < 4; ++x)
delete[] arrayArray[x];
In C++, if you want to delete
a space allocated by new something[]
, you need delete[]
instead of delete
.
Then free the array itself:
delete[] arrayArray;
Upvotes: 3
Reputation: 5831
int** arrayArray;
arrayArray= new int*[4];
The above code initializes 4 locations that can hold pointers to 4 int*
The next couple of lines allocate 4 int spaces for each int*
, so a total of 4*4=16 integer spaces.
for (int x = 0; x < 4; ++x)
{ arrayArray[x] = new int[4];}
Now as per your comment, you want only 4 integer spaces. So that means your 2d array would be 2x2.
So your code should look something like:
int** arrayArray;
arrayArray= new int*[2];
for (int x = 0; x < 2; ++x)
{ arrayArray[x] = new int[2];}
This way you will only allocate 2 int*
locations and 2 int spaces that they can point to.
Upvotes: 0