Pass a two dimensional array to a function of constant parameter

前端 未结 2 1840
陌清茗
陌清茗 2020-11-27 07:33

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

相关标签:
2条回答
  • 2020-11-27 08:12

    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

    0 讨论(0)
  • 2020-11-27 08:22

    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 );
    
    0 讨论(0)
提交回复
热议问题