I have a matrix declared like int **matrix, and I know that the proper way to pass it to a function to allocate memory should be like this:
void AllocMat(int ***mat, int size);
But now I need to delete these memory in another function and am not sure about what to pass:
void DeallocMat(int **mat, int size);
or
void DeallocMat(int ***mat, int size);
I think the second one should be right, but neither way gives me segmentation fault as I tried.
The question is tagged C++, and yet the answers only use the C subset…
Well, first of all, I would recommend against the whole thing. Create a class that encapsulates your matrix and allocate it in a single block, offer
operator()(int,int)to gain access to the elements…But back to the problem. In C++ you should use references rather than pointers to allow the function to change the argument, so your original allocate signature should be:
And call it like:
Or better, just return the pointer:
For the deallocation function, since you don’t need to modify the outer pointer, you can just use:
Now, for a sketch of the C++ solution: