In this article, the author tries to talk about what the names of arrays in C are. It shows that a and &a have the same numeric value, then different types. The name a is a pointer to the first element of the array and is of type int * , and &a is the same as &a[0] , and is a pointer to an array of three numbers.

An example at the end of the article:

 preserve do :escaped (gdb) print a + 1 $10 = (int *) 0x7fff5fbff570 (gdb) print &a + 1 $11 = (int (*)[3]) 0x7fff5fbff578 

And the quotation of the author: Note that it adds twelve!

  1. Why is it written here that 12 is added to &a , when the log shows that 8 is added?

  2. Why does adding one to &a increment the value much more than adding one to a ? What kind of game is this?

  • And what is the sizeof (int *) on your system? - Mike
  • I have four bytes. And the author can see the same, that not 12 is added. - typemoon
  • in fact, 12 is a reference point a[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
  • Here's a similar question: How does the array address get in in C? - Grundy

1 answer 1

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.