I want to write a C function that accepts a dynamic 2D array as input, but does not modify the array.
I try to be correct, but not only to make my code more clear, but because my functions will be called from C ++ code, and C ++ is quite wary of these things.
How to declare a function to take a pointer "const" to a pointer, i.e. how to indicate that the function will not change the contents of the 2d array?
The following is a concrete, super-simple example. I am using a 2D array of twins, i.e. Double ** to represent a square matrix in C of size nxn, and I want to write a function that calculates the trace of one of these matrices:
#include <stdlib.h>
In the above example, both versions of the sqr_matrix_trace () and sqr_matrix_trace_const () trace functions compile cleanly (the latter is the one I prefer, because it clearly demonstrates that there will be no changes in the given matrix), but the call
sqr_matrix_trace_const(a, n)
issues the following warning:
sqr_matrix.c: In function 'main': sqr_matrix.c:44: warning: passing argument 1 of 'sqr_matrix_trace_const' from incompatible pointer type sqr_matrix.c:27: note: expected 'const double * const*' but argument is of type 'double **'
Listing overcomes this:
sqr_matrix_trace_const((const double * const *)a, n)
but it's wrong to use a cast to use to overcome the inconvenience of the compiler.
Alternatively, I could suppress a compiler warning, but this is an error message.
So, I want my code to be compiled, and I want to pass the constant of the dynamic 2D array passed to the function without resorting to customization. This seems like a legitimate aim. Is it possible? If not, what is the standard / accepted practice for this?