Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ delete dynamic matrix

I have this code to allocate and initialize:

nw = new int*[V];

for (w = 0; w < V; w++) {

nw[w] = new int[K];

for (k = 0; k < K; k++) 

  nw[w][k] = 0;
}

and this to free memory:

if (nw) {
 for (int w = 0; w < V; w++) {  
  if (nw[w]) 
delete nw[w];      
}

The program compile and runs, but, when its try to deallocate memory, fails. The program not always fails at the same value of w.

Any ideas?

like image 759
user1705996 Avatar asked Jan 22 '26 11:01

user1705996


1 Answers

When new[] use delete[], so change to:

delete[] nw[w];

and remember to delete[] nw;.

Note that the individual assignment of 0 to each int in the array can be replaced with:

nw[w] = new int[K](); // This value initializes the array, in this
                //^^     case sets all values to zero.

You can avoid explicitly handling dynamic allocation with std::vector<std::vector<int>>:

std::vector<std::vector<int>> nw(V, std::vector<int>(K));
like image 131
hmjd Avatar answered Jan 25 '26 01:01

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!