2

Possible Duplicate:
Why do these two pointer subtractions give different results?

char arr[] = "stackoverflow";
char *p1 = arr;
char *p2 = arr + 3;
printf("%d",  (int*)p2 - (int*)p1);

it's answer is 0..Can you explain why is it so ?

1
  • 1
    Please make sure the code is compilable first...
    – kennytm
    May 31, 2012 at 17:31

3 Answers 3

4

Because p2 - p1 is < sizeof (int). So (int *) p2 - (int *) p1 == 0, the number of int elements between the two pointers.

1
  • thnx man ,I got it !! woo I just missed da part :)
    – vijay
    Jun 1, 2012 at 5:21
3

Because you're invoking implementation-defined/undefined behaviour. An int is probably of size 4 on your platform, so at least one of those pointers is not correctly aligned.

In practice, it's probably because the compiler is doing something like (p2 / 4) - (p1 / 4) under the hood.

6
  • ...or even (p2-p1) & ~3 :-) May 31, 2012 at 17:33
  • Where does ~3 come from?
    – Kylo
    May 31, 2012 at 17:44
  • Isn't it just flat-out undefined behaviour? You're attempting pointer arithmetic on invalid pointers, period.
    – Kerrek SB
    May 31, 2012 at 17:44
  • @Kylo: I'm implying that the compiler throws away the 2 lsbs of each value. Although actually division would make more sense here, so I've edited the answer. May 31, 2012 at 18:21
  • @KerrekSB: Not sure. I'm hedging my bets now! May 31, 2012 at 18:29
0

I think what you probably meant to do is:

printf("%d",  (int)(p2 - p1));

But this does not even require a conversion because the difference between two pointers returns a signed integral type (ptrdiff_t) so you can leave out the typecast and change "%d" to "%td".

1
  • 1
    If you omit the cast you need to use the t length modifier: printf("%td", p2 - p1); The %d is for an int argument.
    – ouah
    May 31, 2012 at 18:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.