Using Pointers in C

#include <stdio.h> int main(void) { int a[5]={1,2,3,4,5}; int *ptr=(int*)(&a+1); printf("%d %d\n",*(a+1),*(ptr-1)); return 0; } 

Output:

 2,5 

I could not understand how *(ptr-1) is evaluated to 5 (output correction). But when I manually it was 1. My understanding of *(ptr-1) would be evaluated to *(&a+1-1) , which would be *(&a) , which is 1.

Please help me understand this concept.

+8
c pointers
source share
2 answers
 int *ptr=(int*)(&a+1); 

does &a + 1 does &a + sizeof (a) since a is an int [5] type that makes ptr point to actually a[5] (invalid / outside of the given limit)

(ptr - 1) thus points to a[4] , and *(ptr - 1) will print 5 .

+9
source share

In your printf you are extracting the value in pos 1, increasing the position with +1 from 0 .

In the second integer, you extract 5 , because &a+1 actually points outside the array, so when you do *(ptr-1) , it returns 5 . If you delete -1 , you will get a really strange result (in my case it was -1078772784 ).

+5
source share

All Articles