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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With