-1

I'm learning about pointers in C and I tried this program in GCC Compiler.
When I try p-q it gives 1 as output (as it takes 4 bytes for int and the values of p and q are 2358844 and 2358840 respectively and hence 1 as output because 1*4=4 bytes after p-q provides 4).
But as soon as I try q-p it gives 4294967295 as output. It should give -1 as output, but I'm unable to understand why it is giving the other output.

This is my program.

#include<stdio.h>
#include<conio.h>
void main()
{
    int a=5,b=6;
    int *p,*q;
    p=&a;
    q=&b;
    printf("p = %u",p);
    printf("\nq = %u",q);
    printf("\nq-p = %u",q-p);
    getch();
} 
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 2
    Technically your program exhibits *undefined behavior*. You should use the `"%p"` format to print pointers. – Some programmer dude Jan 18 '18 at 15:09
  • 3
    In addition you can only subtract pointers that point to elements of the same array. p and q do not, so q - p is undefined too. – n. m. could be an AI Jan 18 '18 at 15:12
  • %p was giving F 16 times. i used %d instead. – vivek bhardwaj Jan 18 '18 at 15:14
  • 1
    Somewhat related: https://stackoverflow.com/q/7954439/5265292 there you can learn something about the correct types and format strings for your pointer testing... strictly speaking, the result may still be undefined behavior since your two ints are not part of the same array (but I'm not 100% sure on that) – grek40 Jan 18 '18 at 15:25
  • 1
    @vivekbhardwaj Who or what text suggested using `"%u"` to print a pointer? – chux - Reinstate Monica Jan 18 '18 at 15:46
  • [using the wrong format specifier invokes undefined behavior](https://stackoverflow.com/q/16864552/995714). Your system has 64-bit pointers but you told `printf` to read only 4 bytes and that *may* mess up your stack. [Subtracting pointers to 2 different ints also invoke undefined behavior](https://stackoverflow.com/q/46891748/995714) https://stackoverflow.com/q/47891629/995714 Besides, the difference between 2 pointers are of type `ptrdiff_t` which [must be printed using `%td`](https://stackoverflow.com/q/7954439/995714) – phuclv Jan 18 '18 at 16:16

1 Answers1

3

4294967295 is FFFFFFFF or -1 as a signed value. You're printing it as unsigned with %u

cleblanc
  • 3,678
  • 1
  • 13
  • 16
  • thank you. i used %d in place of %u and it is giving desired output. – vivek bhardwaj Jan 18 '18 at 15:12
  • @vivekbhardwaj This is seems like the right answer and you've stated it works for you, You should go ahead and accept it unless you're waiting for additional answers. – axwr Jan 18 '18 at 19:05
  • @Scheme it's technically not the right answer. Both `%u` and `%d` are not for printing differences between pointers – phuclv Jan 19 '18 at 06:34