I coding for "pass dynamic 2D to function" with C.
The following code compiles successfully and runs fine.
void iter_2d(const int** arr,
const size_t row,
const size_t column) {
// ..some code
}
int main(){
const size_t column = 3, row = 4;
int** arr = (int**)malloc(sizeof(int*) * row);
for (size_t i = 0; i < row; i++)
arr[i] = (int*)malloc(sizeof(int) * column);
// init val for array
iter_2d(arr,row,column);
// clear array
}
Run Code Online (Sandbox Code Playgroud)
but I get warning:
t.c:24:11: warning: passing argument 1 of 'iter_2d' from incompatible pointer type [-Wincompatible-pointer-types]
iter_2d(arr,row,column);
^~~
t.c:4:26: note: expected 'const int **' but argument is of type 'int **'
void iter_2d(const int** arr,
~~~~~~~~~~~~^~~
Run Code Online (Sandbox Code Playgroud)
I think that function iter_2d just iterate value of array which cannot be modify in function iter_2d,
so input parameter arr should be const to pointer.
But compiler show me this warning made me confused.
The reason a conversion from char ** to const char ** violates constraints is given in the C 2018 standard in 6.5.16.1 6, example 3. Suppose we have:
const char **cpp;
char *p;
const char c = 'A';
Run Code Online (Sandbox Code Playgroud)
Next, consider &p. This is a char **. If we allowed a conversion to const char **, then we could assign it to cpp:
cpp = &p; // Violation of C constraints for assignment.
Run Code Online (Sandbox Code Playgroud)
Suppose we did that. Then cpp is a const char **, so *cpp is a const char *. That means we can assign to it the address of a const char, like this:
*cpp = &c;
Run Code Online (Sandbox Code Playgroud)
Now *cpp is a pointer to c. Since cpp points to p, *cpp is p, which means that p points to c. So now we can do this:
*p = 0;
Run Code Online (Sandbox Code Playgroud)
That changes c, but c is a const char, which we are not supposed to be able to change.
So allowing conversions from char ** to const char ** violates the desired behavior for constant objects.
This example uses assignment expressions, but passing arguments to functions is defined to behave like assigning the arguments to the parameters. The constraints are the same.
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |