My understanding is that
char (*)[20]
is a pointer to an array of 20 non-const chars, while
const char (*)[20]
is a pointer to an array of 20 const chars.
In the following code, I am passing a pointer to an array of non-const chars to a function which expects a pointer to an array of const chars. Inside the function, the compiler properly catches write accesses to the array, as expected:
#include <stdlib.h>
void f(const char (*param)[20]) {
/* correctly catched by the compiler: assignment of read-only location '(*param)[2]' */
/* (*param)[2] = 'A'; */
}
int main() {
char (*data)[20] = calloc(20, 1);
f(data);
return 0;
}
However, I am getting the following warning at the function call:
$ gcc -Wall -pedantic -o so so.c
so.c: In function 'main':
so.c:15:4: warning: passing argument 1 of 'f' from incompatible pointer type [enabled by default]
f(data);
^
so.c:3:6: note: expected 'const char (*)[20]' but argument is of type 'char (*)[20]'
void f(const char (*param)[20]) {
^
Why is that? Should it not always be possible to pass a pointer to non-const data to a function which expects a pointer to const data of the same type?
I know that there are other solutions to this, but I am particularly interested in understanding why the compiler gives this warning in this specific situation.