4
int a[20];

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

(The above" = " means "equal")

Is that right?

Rainer Liao
  • 223
  • 3
  • 13

3 Answers3

7

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

&a is the address of the array. Adding 1 to an address (pointer value) advances it by the size of the type that 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 just past the end of it. (For purposes of pointer arithmetic, a single object is treated as an array of one element.)

If you assume a certain "well-behaved" memory model, with a single linear monolithic addressing space and addresses sensibly related to integers, then given your assumptions (&a is 100, sizeof (int) == 4), then yes, the result of &a + 4 would be 420. More precisely, since 420 is an integer, not a pointer, it would be (int(*)[10])420 -- again, assuming conversions between pointers and integers are particularly well behaved.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
5

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

So &a + 4 is different than a + 4 since in the second expression a evaluates to a pointer to the first element (it evaluates to a pointer of type int*). The pointer arithmetic works out differently since the pointer types are different, even though the value of &a and a are the same.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
3

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

When you add to a pointer, it adds the entire size of the thing you're pointing at for each size.

So, yes. You're right.

xaxxon
  • 19,189
  • 5
  • 50
  • 80