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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With