我从《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
const int ar[][COLS]
与const int (*ar)[COLS]
是相同的。 - juanchopanza