Outputting Code Behavior & in c
In your question, "& a" is the address of the entire array a []. If we add 1 to & a, we get "base address [] + sizeof (a)". And this value is assigned to int *. So ptr points to memory just after 6. ptr is assigned the value "int *" and the value * (ptr-1) is printed. Since ptr points to memory after 6, so ptr - 1 points to 6.
source to share
&a
is the address of the array a
. Adding 1
to it will increase it to one per array (adding 24 bytes). Cast the rotation operator (int*)
to a &a+1
pointer to a type int
. ptr-1
will only decrease ptr
by 4
bytes and so this is the address of the last element of the array a
. Highlighting ptr - 1
will give the last item 6
.
source to share
Yes, because it a
is an array of type int[6]
. Therefore &a
gives you the type int (*)[6]
. This is not the same as a pointer to int, it is a pointer to an array int
.
So, &a + 1
increments the pointer by one of the array sizes, pointing to the last element of the array.
Then, taking the address in ptr
and doing -1
, decrements the address by sizeof(*ptr)
which is equal sizeof(int)
, which gives you the address of the last element in the array.
Finally, remove the reference to this address, you get the value of the last element 6
. Success.
source to share
Since it (int*)(&a + 1)
uses the entire array as a base type and adds 1 full size of the array to it, that is, it adds 24 bytes.
And when you do ptr-1
, since ptr
type is int, it only subtracts 4 bytes. It is very important to remember the pointer type when doing pointer arithmetic.
source to share