【发布时间】:2015-03-19 16:04:52
【问题描述】:
我从C Primer Plus中了解到,如果你想保护一个数组不被函数意外修改,你应该在函数定义的头部中的指针声明之前添加const修饰符。
遵循这个明智的建议,在以下最小示例中,我尝试将非常量二维数组 array 传递给函数 Sum2D,其中一个参数是 pointer-to-const-int[2]。
#include <stdio.h>
#define ROWS 2
#define COLS 2
int Sum2D(const int ar[][COLS], int rows); //use `const` to protect input array
int main(void)
{
int array[ROWS][COLS]={{1,2},{3,4}}; //the non-constant array
printf( "%d\n", Sum2D(array,ROWS) );
return 0;
}
int Sum2D(const int ar[][COLS], int rows)
{
int total=0;
int i,j;
for( i=0 ; i<rows ; i++ )
{
for( j=0 ; j<COLS ; j++ )
{
total+=ar[i][j];
}
}
return total;
}
但是,gcc 在不发出以下警告的情况下无法成功编译此代码:
$gcc -ggdb3 -Wall -Wextra -o test test.c
test.c: In function ‘main’:
test.c:16:2: warning: passing argument 1 of ‘Sum2D’ from incompatible pointer type [enabled by default]
printf( "%d\n", Sum2D(array,4) );
^
test.c:4:5: note: expected ‘const int (*)[4]’ but argument is of type ‘int (*)[4]’
int Sum2D(const int ar[][COLS], int rows);
^
1) 为什么会出现警告?
2)如何消除“噪音”?(除了在array声明中添加const。)
(如果array和函数都使用一维数组,则没有警告。)
系统信息:
Ubuntu 14.04LTS
编译器:gcc 4.8.2
【问题讨论】:
-
非常直接。函数
Sum2D期望接收一个 const 2d 数组,但您给它一个非 const 数组。这可能很危险,但不一定,这就是警告而不是错误的原因。 -
@inneedofhelp 实际上,该函数需要一个 指针 指向
const int大小的 COLS 数组。在函数参数中,const int ar[][COLS]与const int (*ar)[COLS]相同 -
你的参数
rows有什么原因,而不仅仅是使用定义的维度? -
显然 gcc 有他们的警告。 4.9.2 shows no such warnings
-
允许编译器将不符合标准的程序编译为扩展,因此这不会是一个严重的错误,但是如果有人以这种方式编写代码,然后将代码移植到编译器,这可能会很烦人没有扩展名
标签: c arrays pointers gcc-warning