Blog Source: http://hi.baidu.com/casperkid/item/8e7b8f6d2efc910ea1cf0f8b
First look at the following code
#include <stdio.h>
int main (void)
{
int a[5] = {1, 2, 3, 4, 5};
int *ptr1 = (int*) (&a + 1);
int *ptr2 = (int*) ((int) a + 1);
printf ("%x%x\n", Ptr1[-1], *ptr2);
return 0;
}
interested friends can guess what the output value will be =.=~
give the answer "5 2000000"
This involves a problem with the meaning of the C array name and the size-end storage structure
First of all, the first ptr1
It is used to tell the meaning of the C array name
we know that array name a represents the first address of array a.
if the address of a is 0x0012ff6c
then the value of Ptr1 = (int*) (&a) PTR1 is also 0x0012ff6c
but the value of ptr1 = (int*) (&a + 1) ptr1 is 0x0012ff80
Let's take a look at the memory situation.
Let's talk about it. Starting with 0X0012FF6C is the array int a[5]
There are 1, 2, 3, 4, 5 can see ha ~
the value of Ptr1 becomes 0x0012ff80.
can you figure out why?
In fact, the array name A also has a layer of meaning
simply to make an analogy.
const int *a;
a = (int*) malloc (5 * sizeof (int));
This is another version of our int a[5]
you can see that the array name A has a layer of meaning that governs the area it belongs to .
&a + 1 is not a simple 0x12ff6c + 1 Oh
It's not 0X12FF6C + 4 (int)
instead, the range of 0X12FF6C + < array a >
i.e. 0x12ff6c + 5* (int), 0x12ff6c + 0x14 = 0x12ff80
so the array name A is also given its area when it initially allocates space.
&a + 1 in +1 is the amount of space governed by the span array name a
so ptr1 now points to 0x0012ff80 .
If the output *ptr1 is 0x0012ff6c
and the last Ptr[-1] is 0x0012ff80-4 (int) = 0x0012ff7c
The 0x0012ff7c value is the 5 we get.
----------------------------------------------------------------------------------------------------
and then a second ptr2 .
output of 2000000 a lot of people would find it strange that they didn't have that value.
so it's easy to understand the big-endian and small-end storage patterns.
Let's take a look at the memory situation and analyze it.
my CPU is AMD from the diagram can also be seen in the use of small-end storage mode
ptr2 = (int*) ((int) A + 1)
First (int) A is the first address of array a
but notice here that the meaning of &a and (int) A is different, so it makes +1 different.
the value of (int) A is 0x0012ff6c, which points to a[0]
the value of a[0] is 1 memory distribution is the case
0x0012ff6a , xx, xx xx
then (int) A + 1 and the area span without the first case is simply +1byte
SO (int) A + 1 is 0x0012ff6c + 1 = 0x0012ff6d
because it is the address that is pointing, take 4Byte continuously as the value
the memory condition that PTR2 now points to is
0x0012ff6a , xx, xx xx
because it's a small-end storage structure
So the output naturally becomes 2000000.