Int a [20], what is the answer "& a + 4"?

int a[20]; 

Suppose that the address [20] in memory is 100. The size of int is 4. It is easy to see that a = 100, &a = 100, &a[4] = 116 . But when I try (& a + 4), the answer is 420 (I test it in GCC, DEV-C, VC) I think the reason why &a + 4 = 420 420 = 100 + 4 * sizeof (a[20]) = 100 + 4*(4*20)

(The above "=" means "equal to")

Is it correct?

+4
source share
3 answers

Strictly speaking, the answer is that the behavior is undefined.

&a is the address of the array. Adding 1 to the address (pointer value) advances it in the size of the type it points to. But pointer arithmetic is valid only when the result points to an element of the same array as the original pointer, or only beyond its end. (For the purpose of pointer arithmetic, one object is considered an array of one element.)

If you assume a certain model of "good behavior" with one linear monolithic address space and addresses reasonably related to integers, then, given your assumptions ( &a is 100, sizeof (int) == 4 ), then yes, the result is &a + 4 will be 420 . More precisely, since 420 is an integer, not a pointer, it will be (int(*)[10])420 - again, assuming that conversions between pointers and integers behave especially well.

+7
source

&a is a pointer to an array of int with 20 elements (type int (*)[20] ).

So, &a + 4 is different from a + 4 , because in the second expression a , a pointer to the first element is computed (it computes a pointer of type int* ). Arithmetic pointer operates differently since different types of pointers, although the values &a and a are the same.

+5
source

Since size a is the size of the array, which is 80 bytes. Thus, 4 * 80 = 320 + base address 100 = 420.

When you add a pointer, it adds the entire size of the object you are pointing to for each size.

So yes. You're right.

+3
source

Source: https://habr.com/ru/post/1487596/


All Articles