Array of pointers to multidimensional arrays

后端 未结 3 1956
长发绾君心
长发绾君心 2021-02-10 19:38

i have some bidimensional arrays like:

int shape1[3][5] =  {1,0,0,
             1,0,0,
             1,0,0,
             1,0,0,
             1,0,0};
int shape2[3]         


        
3条回答
  •  天命终不由人
    2021-02-10 20:22

    First of all, the first array bound refers to the outermost array dimension, so you should probably declare shape1 as:

    int shape1[5][3] =  {1,0,0,
                         1,0,0,
                         1,0,0,
                         1,0,0,
                         1,0,0};
    

    and similarly for shape2.

    [EDIT: I've changed the type of shapes below to correspond to Robert Barnes' answer -- we don't want the outermost subscript to be included in this type!]

    The slightly strange-looking typename you need is:

    int (*shapes[])[3] = { shape1, shape2 };
    

    This allows the element at row 4, column 1 of shape2 to be addressed using

    shapes[1][3][0]
    

    Breakdown of subexpressions and their C types:

    shapes            // has type "int (*x[2])[3]" (decays to "(**x)[3]")
    shapes[1]         // has type "int (*x)[3]"
    shapes[1][3]      // has type "int x[3]" (decays to "int *x")
    shapes[1][3][0]   // has type "int x"
    

    (Note that a dummy x has been included in the types above to make them clearer -- in fact this identifier is not part of the type.)

    A rule of thumb for decoding C/C++ types is "starting from the variable name, read right when you can and left when you hit a closing parenthesis." So the decoded typename for shapes is:

    An array of pointers to an array of 3 integers.

    In general it's much nicer to use typedefs for these complicated types, as dirkgently suggests.

提交回复
热议问题