Reputation: 43
I came across a code whoes output I'm not able to understand.The code is-
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1);
printf("%d ", *(ptr-1) );
return 0;
}
The output of above code is coming out 6, but i think that it should be 1. Please explain why it is 6.
Upvotes: 3
Views: 70
Reputation: 2122
Because (int*)(&a + 1)
uses the whole array as the base type and adds 1 whole size of an array to the address , i.e. adding 24 bytes.
And when you do ptr-1
since ptr
type is int it will subtract only 4 bytes.
Its very important to remember the type of the pointer while doing pointer arithmetic.
Upvotes: 0
Reputation: 134336
Yes, because a
is an array having a type int[6]
. Therefore, &a
gives you the type int (*)[6]
. It is not same as pointer to int, it is a pointer to int
array.
So, &a + 1
increments the pointer by one of the the array size, pointing past the last element of the array.
Then, taking the address in ptr
and doing a -1
, decreases the address by a sizeof(*ptr)
which is sizeof(int)
, which gives you the address of last element on the array.
Finally, de-referencing that address, you get the value of the last element , 6
. Success.
Upvotes: 0
Reputation: 287
In your question "&a" is address of the whole array a[]. If we add 1 to &a, we get “base address of a[] + sizeof(a)”. And this value is typecasted to int *. So ptr points to the memory just after 6 . ptr is typecasted to "int *" and value of *(ptr-1) is printed. Since ptr points memory after 6,so ptr – 1 points to 6.
Upvotes: 3
Reputation: 106012
&a
is an address of array a
. Adding 1
to it will increment it to one past the array (adding 24-bytes). Cast operator (int*)
cast &a+1
to pointer to int
type. ptr-1
will decrement ptr
by 4
bytes only and therefore it is the address of last element of array a
. Dereferencing ptr - 1
will give the last element which is 6
.
Upvotes: 2