The value of “multidimensional array pointer +1” doesn't match

前端 未结 2 915
花落未央
花落未央 2021-01-29 12:18

Here is the problem program:

#include 
int main()
{   
    int apricot[2][3][5];
    int (*r)[5]=apricot[0];
    int *t=apricot[0][0];

    printf         


        
2条回答
  •  生来不讨喜
    2021-01-29 12:55

    You get tricked by the C syntax. r is an array pointer to an array of int, t is a plain int pointer. When doing any kind of pointer arithmetic, you do it in the unit pointed at.

    Thus t+1 means the address of t + the size of one pointed-at object. Since t points at int and int is 4 bytes on your system, you get an address 4 bytes from t.

    The same rule applies to r. It is a pointer to an array of 5 int. When you do pointer arithmetic on it by r+1, you get the size of the pointed-at object, which has size 5*sizeof(int), which happens to be 20 bytes on your computer. So therefore r+1 gives you an address 20 bytes (==14 hex) from r.

提交回复
热议问题