问题描述
我有一个函数采取静态二维阵列和处理该数组的元素的元素作为是常数:
I have a function taking a static two-dimensional array and treating the elements of the elements of the array as being constant:
void test_function(const char arr[3][3]);
我试图调用这样的功能如下:
I am trying to call such a function as follows:
char my_var[3][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
test_function(my_var);
在用gcc编译(没有任何标志),我得到以下警告:
When compiling with gcc (without any flag), I get the following warning:
test.c:9:8: warning: passing argument 1 of 'test_function' from incompatible pointer type
test_function(my_var);
^
test.c:4:6: note: expected 'const char (*)[3]' but argument is of type 'char (*)[3]'
void test_function(const char arr[3][3]);
如果我删除 test_function
的常量
的原型,警告消失。但它不是我真正想要的东西。
If I remove the const
from test_function
's prototype, the warning goes away. But it is not really what I want.
在与铿锵编译既 -pedantic-错误
和 -Wall
我没有得到任何警告指针不兼容。
When compiling with clang with both -pedantic-errors
and -Wall
I don't get any warning about pointer incompatibility.
我只是想明白为什么GCC输出在这种情况下,这样的警告。
为什么我的指针/阵列是不相容的?
I just would like to understand why gcc outputs such a warning in this case.Why would my pointers/arrays be incompatible?
推荐答案
GCC是正确的,标准的文字和锵是错误的。
GCC is right to the letter of the standard and Clang is wrong.
6.3.2.3/2:
6.3.2.3/2:
有关任何限定的①的,一个指针指向一个非Q限定类型可被转换成一个指针的①的类型-qualified版本;
看起来非常有前途。但是坚持下去。
Looks very promising. But hold on.
6.2.5 / 26:
6.2.5/26:
一个派生类型不被限定符合格(如果有的话)从其所衍生的类型的
作为专门应用于阵列的标准的这一规定是没有必要的,并且可以容易地反转。也就是说,为const char [3]
可以很容易地取得的常量限定版的char [3]
。但事实并非如此。他们只是不同的,不兼容的类型。事实上,有C中没有const限定的数组类型可言,所以你不能有的常量限定版的char [3]
。这就是我们有标准的,必须一起生活。
This provision of the standard as applied specifically to arrays is not necessary, and could be easily reversed. That is, const char[3]
could be easily made a const-qualified version of char[3]
. But it is not. They are just different, incompatible types. In fact there are no const-qualified array types in C at all, so you can't have a const-qualified version of char[3]
. That's the standard we have and must live with.
这篇关于不兼容的指针类型和常量性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!