8
#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 the *(ptr-1) evaluated to 5 (correct output). But when I manually did it was 1. My understanding is *(ptr-1) will get evaluated to *(&a+1-1) which would be *(&a) which is 1.

Please help me to understand this concept.

4
  • 13
    (&a + 1) != (&a[0] + 1) Commented Aug 25, 2011 at 17:09
  • 4
    &a has type pointer to array of 5 ints, not pointer to int. Your cast here is hiding your mistake. Commented Aug 25, 2011 at 17:11
  • Why do you want to point to the address of an address? Commented Aug 25, 2011 at 17:30
  • What is 'yashwant kanetkar'? How is it relevant to the question? Commented Aug 25, 2011 at 18:08

2 Answers 2

8
int *ptr=(int*)(&a+1);

makes &a + 1 makes &a + sizeof (a) as a is type of int [5] which makes ptr to point to actually a[5] (invalid/beyond the defined limit)

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

Sign up to request clarification or add additional context in comments.

Comments

5

In your printf, you are retrieving the value in pos 1 by incrementing the position with +1 from 0.

In your second integer, you are retrieving 5 because &a+1 actually points beyond the array, so when you do *(ptr-1), it returns 5. If you remove the -1, then you get a really weird result (in my case it was -1078772784).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.