When int a[3] has been defined, is there any difference between int* b = a and int (*c)[3] = &a

后端 未结 3 1377
小鲜肉
小鲜肉 2021-01-27 07:06

I\'m trying to deepen my understanding on syntax relevant to pointer in C, and I noticed that If I created an array of int first, int(*)[] is a way of giving a poin

3条回答
  •  醉话见心
    2021-01-27 08:03

    Let's start with a visual representation of what's going on:

               int [3]    int *     int (*)[3]
               -------    -----     ----------
       +---+
       |   |   a[0]       b[0]      c[0]
       + - +
       |   |   a[1]       b[1]
       + - +
       | 3 |   a[2]       b[2]
       +---+
       |   |                        c[1]
       + - +
       |   |
       + - +
       |   |
       +---+
       |   |                        c[2]
       + - +
       |   |
       + - +
       |   |
       +---+
    

    On the far left is a view of memory as a sequence of 3-element arrays of int The remaining columns show how each of a[i], b[i], and c[i] are interpreted.

    Since a is declared as int [3] and b is declared as int *, each a[i] and b[i] have type int (a[i] == *(a + i)).

    But c is different - since c is declared as "pointer to 3-element array of int" (int (*)[3]), then each c[i] has type "3-element array of int" (int [3]). So instead of being the third element of a, c[2] is the first element of the third 3-element array following a.

提交回复
热议问题