Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int a[20], what's the answer of " &a + 4"?

Tags:

arrays

c

pointers

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?

like image 483
Rainer Liao Avatar asked Dec 07 '22 07:12

Rainer Liao


1 Answers

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.

like image 142
Keith Thompson Avatar answered Dec 25 '22 05:12

Keith Thompson