What do parentheses in a C variable declaration mean?

前端 未结 5 1057
忘了有多久
忘了有多久 2020-12-04 19:23

Can someone explain what this means?

int (*data[2])[2];
5条回答
  •  萌比男神i
    2020-12-04 20:20

    What are the parentheses for?

    In C brackets [] have a higher precedence than the asterisk *

    Good explanation from Wikipedia:

    To declare a variable as being a pointer to an array, we must make use of parentheses. This is because in C brackets ([]) have higher precedence than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this:

    double (*elephant)[20];
    

    This declares that elephant is a pointer, and the type it points at is an array of 20 double values.

    To declare a pointer to an array of pointers, simply combine the notations.

    int *(*crocodile)[15];
    

    Source.

    And your actual case:

    int (*data[2])[5];
    

    data is an array of 2 elements. Each element contains a pointer to an array of 5 ints.

    So you you could have in code using your 'data' type:

    int (*data[2])[5];
    int x1[5];
    data[0] = &x1;
    data[1] = &x1;
    
    data[2] = &x1;//<--- out of bounds, crash data has no 3rd element
    int y1[10];
    data[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10]
    

提交回复
热议问题