Pass a two dimensional array to a function of constant parameter

浪子不回头ぞ 提交于 2019-11-26 23:03:40

This is an unfortunate "bug" in C's design; T (*p)[N] does not implicitly convert to T const (*p)[N]. You will have to either use an ugly cast, or have the function parameter not accept const.


At first sight it looks like this conversion should be legal. C11 6.3.2.3/2:

For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type;

However also look at C11 6.7.3/9 (was /8 in C99):

If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type.

This last quote says that int const[4] is not considered to be a const-qualified version of int[4]. Actually it is a non-const-qualified array of 4 const ints. int[4] and int const[4] are arrays of different element types.

So 6.3.2.3/2 does not in fact permit int (*)[4] to be converted to int const (*)[4].


Another weird situation where this issue with const and arrays shows up is when typedefs are in use; for example:

typedef int X[5];
void func1( X const x );
void func1( int const x[5] );

This would cause a compiler error: X const x means that x is const, but it is pointing to an array of non-const ints; whereas int const x[5] means x is not const but it is pointing to an array of const ints!

Further reading here, thanks to @JensGustedt

Karthikeyan.R.S

You can type cast the array while calling the function. It will not automatically convert non-const into const. You can use this.

Sum2D( (const int (*)[])array, ROWS );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!