How pointer to array works?

后端 未结 2 831
故里飘歌
故里飘歌 2021-01-17 08:23
int s[4][2] = {
                  {1234, 56},
                  {1212, 33},
                  {1434, 80},
                  {1312, 78}
              };

int (*p)[1];         


        
2条回答
  •  长发绾君心
    2021-01-17 09:02

    This is the way arrays work in C -- arrays are not first class types, in that you can't do anything with them other than declaring them and getting their size. In any other context, when you use an expression with type array (of anything) it is silently converted into a pointer to the array's first element. This is often referred to as an array "decaying" into a pointer.

    So lets look at your statements one by one:

    p = s[0];
    

    Here, s has array type (it's an int[4][2] -- a 2D int array), so its silently converted into a pointer to its first element (an int (*)[2], pointing at the word containing 1234). You then index this with [0] which adds 0 * sizeof(int [2]) bytes to the pointer, and then dereferences it, giving you an int [2] (1D array of 2 ints). Since this is an array, its silently converted into a pointer to its first element (an int * pointing at 1234). Note that this is the same pointer as before the index, just the pointed at type is different.

    You then assign this int * to p, which was declared as int (*)[1]. Since C allows assigning any pointer to any other pointer (even if the pointed at types are different), this works, but any reasonable compiler will give you a type mismatch warning.

    p now points at the word containing 1234 (the same place the pointer you get from s points at)

    printf("%d\n", *(*(p+0)));
    

    This first adds 0*sizeof(int[1]) to p and dereferences it, giving an array (int[1]) that immediately decays to a pointer to its first element (an int * still pointing at the same place). THAT pointer is then dereferenced, giving the int value 1234 which is printed.

    printf("%d\n", *(s[0]+0));
    

    We have s[0] again which via the multiple decay and dereference process noted in the description of the first line, becomes an int * pointing at 1234. We add 0*sizeof(int) to it, and then dereference, giving the integer 1234.

    printf("%u\n", p);
    

    p is a pointer, so the address of the pointer is simply printed.

    printf("%u\n",*p)
    

    p is dereferenced, giving an int [1] (1D integer array) which decays into a pointer to its first element. That pointer is then printed.

提交回复
热议问题