Regarding the first question
Why is it written here that 12 is added to & a, when the log shows that 8 is added?
It should be noted that the results of addition are displayed in the log, and the difference between them is really 8 and this is misleading. But to find out how much has increased, you need to look at the starting address.
= preserve do :escaped (gdb) x/4xb a 0x7fff5fbff56c: 0x01 0x00 0x00 0x00 (gdb) x/4xb &a 0x7fff5fbff56c: 0x01 0x00 0x00 0x00
And if you look at the difference with respect to it, you can see that in the first case it is equal to 4
, and in the second - 12
as written in the article.
As for the second question
Why does adding one to & a increment the value much more than adding one to a? What kind of game is this?
it might help to translate a similar question in English
The array name is usually calculated as the address of the first element, so that array
and &array
have the same value (but different types, array+1
and &array+1
will not be equal if the length of the array is more than one element).
There are two exceptions to this rule: when the array name is the operand sizeof
or unary &
(address-of) the name points to the array itself, so sizeof
returns the size of the entire array, not the size of the pointer.
For an array defined as T array[size]
, array
will be of type T *
. When incrementing it, you will get the next element in the array.
&array
returns the same address, but the pointer type will already be T(*)[size]
- i.e. it is a pointer to the entire array, not a single element. And when you increase this pointer, it adds the size of the entire array, rather than the size of an individual item.
12
is a reference pointa[0]
, in the example above, the address is for a [1], and since the int is 4 bytes and the difference between the addresses given is 8, we end up with 12 - Grundy