1

please explain the output of the below mentioned program. I thought that output should be 1 but it is not 1

#include <stdio.h>

int main()
{
    int  a[] = {1, 2, 3, 4, 5, 6};
    int *ptr = (int*)(&a+1);

    printf("%d ", *(ptr-1));
    getchar(); 

    return 0;
} 
3
  • output should be 1 but it is not 1...so what is it? Commented Apr 15, 2015 at 19:29
  • You may want to include more information, including the actual output you received. Commented Apr 15, 2015 at 19:32
  • 2
    type of &a is int (*)[6]. it meant pointer to int[6]. so &a + 1 point to next(a[6]) the last element(6:a[5]). then cast to int * then -1 so point to last element 6. Commented Apr 15, 2015 at 19:41

2 Answers 2

3

It's because &a has type int(*)[6] and hence &a + 1 != &a[0] + 1 which is what you meant, given your expected output.

If you print the addresses &a and &a[0], they will be the same, however incrementing &a is not the same as incrementing &a[0] because sizeof(int) != sizeof(int *), although that's not always true, your code should not assume it is, or depend on that.

Also, it appears that your are using the cast because your compiler was complaining about the fact that &a is of an incompatible pointer type, you should not need the cast if the pointers are of compatible types so

#include <stdio.h>

int main()
{
    int  a[] = {1, 2, 3, 4, 5, 6};
    int *ptr = &a[0] + 1;

    printf("%d\n", *(ptr-1));

    return 0;
}

should compile just find, and the output will be 1 as you expected.

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

4 Comments

The downvoter seems to disagree, I would like to see your answer to see if mine is really wrong or bad.
i am having the confusion around the same thing.. can you please elucidate it little more
Not sure why this was voted down. Would be interested to see the downvoter comment on their reasoning.
More precisely, &a has type int(*)[6] (now fixed, thanks). Also, sizeof(int) != sizeof(int *) -- sizeof (int*) is irrelevant. What's relevant is sizeof (int[6]).
1

a and &a are the same value,
a is of type int [6],
&a is of type int (*)[6].

It means that

    ptr
 == (int *)(          &a + 1                )
 == (int *)( (char *) &a + 1*sizeof(*&a)    )
 == (int *)( (char *) &a + 1*sizeof(a)      )
 == (int *)( (char *) &a + 1*6*sizeof(int)  )
 == (int *)( (char *) a  + 1*6*sizeof(int)  )
 == (int *)( (char *) a  + 1*6*sizeof(*a)   )
 == (int *)(          a  + 6                )
 == &a[6]

thus

*(ptr-1) == *(a+5) == a[5] == 6

the reason why "6 " is printed.

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.