c - Pass a two dimensional array to a function of constant parameter -
i learned c primer plus if want protect array being accidentally modified function, should add const
modifier before pointer declaration in header of function definition.
following sensible advice, in following minimal example, i'm trying pass non-constant two-dimensional array array
function sum2d
, 1 parameter of pointer-to-const-int[2]
.
#include <stdio.h> #define rows 2 #define cols 2 int sum2d(const int ar[][cols], int rows); //use `const` 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 compile code without issuing 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’ incompatible pointer type [enabled default] printf( "%d\n", sum2d(array,4) ); ^ test.c:4:5: note: expected ‘const int (*)[4]’ argument of type ‘int (*)[4]’ int sum2d(const int ar[][cols], int rows); ^
1) why warning?
2) how can eliminate "noise"?(apart adding const
array
declaration.)
(if array
, function both use one-dimensional array, there no warning.)
system information:
ubuntu 14.04lts
compiler: gcc 4.8.2
this unfortunate "bug" in c's design; t (*p)[n]
not implicitly convert t const (*p)[n]
. have either use ugly cast, or have function parameter not accept const
.
at first sight looks conversion should legal. c11 6.3.2.3/2:
for qualifier q, pointer non-q-qualified type may converted pointer q-qualified version of type;
however @ c11 6.7.3/9 (was /8 in c99):
if specification of array type includes type qualifiers, element type so-qualified, not array type.
this last quote says int const[4]
not considered const
-qualified version of int[4]
. non-const
-qualified array of 4 const int
s. int[4]
, int const[4]
arrays of different element types.
so 6.3.2.3/2 not in fact permit int (*)[4]
converted int const (*)[4]
.
another weird situation issue const
, arrays shows when typedefs in use; example:
typedef int x[5]; void func1( x const x ); void func1( int const x[5] );
this cause compiler error: x const x
means x
const, pointing array of non-const int
s; whereas int const x[5]
means x
not const pointing array of const ints!
further reading here, @jensgustedt
Comments
Post a Comment