Reputation: 3751
I have a function which deallocates a cubic matrix of double
:
free_matrix(double ***U, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
free(U[i][j]);
}
free(U[i]);
}
free(U);
}
Then I have a cubic matrix of integer int ***matrix;
. Compiler gives me an error when I call free_matrix(matrix,n)
but I don't want to duplicate the previous function which only deallocates elements. Is it correct/good/safe to simply cast it like this?
free_matrix((double ***)matrix,n);
Upvotes: 1
Views: 98
Reputation: 8032
What you propose is in general not safe, as noted by @ecatmur. I would rather try to change the interface of your C function to something like the following (I assume 2D for simplicity):
int ** imatrix_alloc(size_t nrows, size_t ncols);
double ** dmatrix_alloc(size_t nrows, size_t ncols);
void matrix_free (void * matrix);
and use it in client code like:
int ** imat = imatrix_alloc(10,20);
double ** fmat = dmatrix_alloc(30,20);
...
matrix_free(imat);
matrix_free(fmat);
The tricky point in the allocation will be to pre-compute all the space you need and allocate it with a single call to malloc
. Then you should initialized pointers appropriately. If you do this matrix_free
can be implemented as a simple wrapper to free:
void matrix_free (void * matrix) {
free(matrix);
}
Upvotes: 0
Reputation: 157374
Unfortunately not; per 6.2.5p28:
[...] Pointers to other types need not have the same representation or alignment requirements.
So there is no guarantee that a int **
can be indexed the same way as a double **
, because int *
and double *
might e.g. have different sizes.
Upvotes: 8