Reputation: 1415
In simple 1D array:
node *nodes = new node[MAX_NODES];
Deleting by:
delete [] nodes;
Deletes all the nodes allocated in the array.
But in this case:
float (*buildingArray)[3] = new float[10][3];
Does this statement make buildingArray
a single dimension array of 3 float pointers? And this is the deallocation line:
delete[] buildingArray;
Does the above deallocation delete
the array, but I am doubtful about whether it will delete its references?
Upvotes: 5
Views: 25626
Reputation: 40613
new float[10][3]
allocates an array of 10 arrays of 3 floats
and returns a pointer to the first element (which is an array of 3 floats).
Calling delete[]
on this pointer causes the whole array to be deleted.
The only difference between the two cases is that in the first case, the type of the values stored in the dynamically allocated array is float
and in the second case the type is float[3]
.
Upvotes: 2
Reputation: 206508
Does the above de-allocation delete the array?
Yes it does.
Simply follow the rule:
You need to call delete
or delete []
as many times you called new
or new []
respectively.
If you had an array of pointers where each index was allocated dynamic memory, you would need to explicitly loop through it and deallocate each array element explicitly.
On a side note you are much better off using a std::vector
or std::array
rather than dynamically allocated array.
Upvotes: 16
Reputation: 7456
Yes it does. The explanation is because there is no information in memory about how much dimensions your array has.
If you have a 3*4 items array, it's exactly the same as a 12 items array. It's just the way you address the specific elements (which are stored in a line after line fashion) that changes.
So delete[]
will work perfectly.
But using new
and delete
operators is not so common these days with smart pointers, unless you really have a good reason to control allocation yourself.
Upvotes: 3