Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete this 2D array in c++

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?

like image 456
Anubha Avatar asked Feb 23 '13 06:02

Anubha


People also ask

Do I need to delete arrays in C?

In C, if you are declaring your array as static ex: int a[10], no need to delete. It will be freed when your function ends or program terminates.

How do you delete a dynamic array?

To delete a dynamic array, the delete or delete[] operator is used. It deallocates the memory from heap. The delete[] keyword deletes the array pointed by the given pointer. Therefore, to delete a dynamically allocated array, we use the delete[] operator.

What is 2D array in C example?

Here i and j are the size of the two dimensions, i.e i denotes the number of rows while j denotes the number of columns. Example: int A[10][20]; Here we declare a two-dimensional array in C, named A which has 10 rows and 20 columns.

Can you use Delete on an array?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression.


1 Answers

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.

like image 97
Alok Save Avatar answered Oct 12 '22 04:10

Alok Save