Last night, a small partner asked a question, feeling very classic.
1 inta[5] = {1,2,3,4,5};2 3 int*ptr = (int*) (&a +1);4 5printf"%d%d \n\r", * (A +1), * (PTR-1) );
From the memory distribution angle to resolve:
&a and a Do the right value when the difference:
&a is the first address of the entire array, and a is the first address of the first element of the array . The two are equal in numbers, but have different meanings. Different meanings can cause them to behave differently when they are involved in the operation.
int *ptr= (int *) (&a + 1);
&a is an array pointer whose type is int (*) [5]; so &a+1 is int (*) [5] + 1 as shown ,
&a+1 is equivalent to the entire array pointer plus 1, after executing &a+1, the PTR offset is equivalent to a + sizeof (int) * 5 * 1.
&a+2 is equivalent to the entire array pointer plus 2, after executing &a+2, the PTR offset is equivalent to a + sizeof (int) * 5 * 2.
int *ptr=(int *)(&a + 1);
Why do you need to force type conversions here, because the type does not match Ah, &a is an int (*) [5];ptr is an int * type. It is because of this coercion type conversion, so printf ("%d%d \n\r", * (A + 1), * (ptr-1));
Here ptr-1 is the last element of a sizeof (int) or a[5]. Some people can't figure out why-1 why not reduce to &a, is because here coercion type conversion . The main combination of two diagrams to understand, easy to understand.
Array memory & array name +1