I've written the following function in C to print out a dynamically created matrix but guarantee that inside the function I
- Can't modify the pointer I'm given
- Can't modify any of the interior pointers
- Can't modify any of the numbers in the matrix
void const2dPrinter(const int *const *const mat, const int numRows, const int numCols){
for(int i =0; i < numRows; ++i){
for(int j =0; j < numCols; ++j){
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
I attempt to call the function in main as follows
int main(){
int numRows = 3;
int numCols = 4;
int** mat = (int**) malloc(numRows * sizeof(int*);
for(int i = 0; i < numRows; ++i){
mat[i] = (int*)malloc(numCols * sizeof(int));
for(int j = 0; j < numCols; ++j){
mat[i][j] = (i +1) * (j+1);
}
}
const2dPrinter(mat, numRows, numCols);
...
}
But I get the following error from the compiler
error: passing argument 1 of 'const2dPrinter' from incompatible pointer type [-Werror=incompatible-pointer-types]
const2dPrinter(mat, numRows, numCols);
note: expected 'const int * const* const' but argument is of type 'int **'
void const2dPrinter(const int *const *const const mat, const int numRows, const int numCols)
My IDE gives the following error:
Parameter type mismatch: Assigning int** to const int* const* const* discards const qualifier.
The code will work if I remove the first const in the declararation of the function. Going from void const2dPrinter(const int *const *const mat, ...){
to void const2dPrinter(int *const *const mat, ...){
but then I'm able to modify the values of the matrix in const2dPrinter, which I don't want to be able to do.
I know that I can cast the int**
to a const int *const *const
when calling the function to get things to work as shown below, but I'm incredibly confused as to why what I have right now doesn't work as everything I have read says that you should be able to have a const pointer point at at a non const value.
const2dPrinter((const int* const* const) mat, numRows, numCols); //this works
I've tried searching for a solution but haven't been able to find one. The code will compile on a C++ compiler without issue but won't work on my C compiler (gcc).
Any advice on how to fix my problem as well as an explanation of why what I have now doesn't work would be greatly appreciated.