I learned from C Primer Plus that if you want to protect an array from being accidentally modified by a function, you should add const
modifier before the pointer declaration in the header of function definition.
Following this sensible advice, in the following minimal example, I'm trying to pass a non-constant two-dimensional array array
to the function Sum2D
, one parameter of which is a 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;
}
However, gcc
cannot successfully compile this code without issuing the following warnings:
$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) Why the warning?
2) How can I eliminate the "noise"?(Apart from adding const
to array
declaration.)
(If the array
and function both use one-dimensional array, there is no warning.)
System information:
Ubuntu 14.04LTS
Compiler: gcc 4.8.2