Output is 2 5Code:int main() { int a[5]={1,2,3,4,5}; int *p=(int *)(&a+1); printf("%d %d",*(a+1),*(p-1)); return 0; }
Please explain...
Output is 2 5Code:int main() { int a[5]={1,2,3,4,5}; int *p=(int *)(&a+1); printf("%d %d",*(a+1),*(p-1)); return 0; }
Please explain...
Most probably &a is the address of an array of 5 int's, so if you add 1 to it, you'll be one integer beyond the end of the array. Compare to &a[0] + 1, or a + 1
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
a is array of ints so in expression a+1 - it is casted to pointer to int and then moved (so a+1 points to the second element of the array
when dereferencing*(a+1) - you get the value of the element - 2
&a is pointer to array of ints, so when moving it (&a+1) ... could you continue?
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
I think you meant
The variable a can become a pointer in pointer contexts, rather than an array. The expression (&a + 1) results in a pointer to pointer, which explains why you needed the cast.Code:int a[5] = { 1, 2, 3, 4, 5 }; int * p = a + 1; printf("%d %d", *(a + 1), *(p - 1));
You're assigning p to an area after the end of the array, and when you dereference *(p - 1) you get your output because of pointer arithmetic. I think the compiler decided to backtrack by the size of your array.
This question is one example why it's not smart to cast in C unless you're sure it's right.
Anyone else please?
I need explanation with *(p-1)
How it is giving 5 as output.
Yes thanks but how p is pointing one int past the end of the array.
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
Remember, pointer arithmetic moves by the thing pointed to. If p is a pointer to int (which it is), then p-1 moves back one int. Since &a is a pointer-to-array-of-five-ints, &a + 1 moves forward one array of five ints, which moves it past the entire array.