I learned from C Primer Plus that if you want to protect an array from being accidentally modified by a function, you should add const
modifier before
This is an unfortunate "bug" in C's design; T (*p)[N]
does not implicitly convert to T const (*p)[N]
. You will have to either use an ugly cast, or have the function parameter not accept const
.
At first sight it looks like this conversion should be legal. C11 6.3.2.3/2:
For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type;
However also look at C11 6.7.3/9 (was /8 in C99):
If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type.
This last quote says that int const[4]
is not considered to be a const
-qualified version of int[4]
. Actually it is a non-const
-qualified array of 4 const int
s. int[4]
and int const[4]
are arrays of different element types.
So 6.3.2.3/2 does not in fact permit int (*)[4]
to be converted to int const (*)[4]
.
Another weird situation where this issue with const
and arrays shows up is when typedefs are in use; for example:
typedef int X[5];
void func1( X const x );
void func1( int const x[5] );
This would cause a compiler error: X const x
means that x
is const, but it is pointing to an array of non-const int
s; whereas int const x[5]
means x
is not const but it is pointing to an array of const ints!
Further reading here, thanks to @JensGustedt
You can type cast the array while calling the function. It will not automatically convert non-const into const. You can use this.
Sum2D( (const int (*)[])array, ROWS );