0

I have a program question, here is the code.

int main() { int *p,*q; p=(int*)1000; printf("%d ",p); q=(int*)2000; printf("%d",q); printf("%d",(p-q)); return 0; } 

But answer coming as

1000 2000 -250 

I am unable to understand what happen with p-q and why answer came as -250?

1
  • 2
    Note that printing pointers with the %d format specifier invokes undefined behaviour. You can print void* with the %p format specifier, printf("%p ", (void*)p);, or you can cast the pointer to an integer type before printing, printf("%" PRIdPTR " ", (intptr_t)p);. For the pointer difference, printf("%td ", (p-q));. Commented Jul 31, 2012 at 20:26

4 Answers 4

12

Correct but probably useless answer: p - q is equal to (1000 - 2000) / (sizeof int). For most C compiles, sizeof int is 4.

Potentially more useful answer: the effect of typecasts like (int*) 1000 is undefined. That code creates a pointer to an int at address 1000. That address is probably invalid. To create a pointer to an int with value 1000, write this:

int i = 1000; int *p = &i; 

Now p points to i, and *p, the value pointed to by p, is 1000.

Here is some correct code that may say what you meant:

int main() { int i = 1000; int j = 2000; int *p = &i; int *q = &j; printf("i = %d *p = %d\n", i, *p); printf("j = %d *q = %d\n", j, *q); printf("*p - *q = %d\n", *p - *q); } 
Sign up to request clarification or add additional context in comments.

Comments

6

When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them.

On your platform, an int is 4 bytes. There are -250 elements between address 2000 and address 1000.

Since p and q don't both point to the same array, the result is undefined. You could get any result, including the one you expect.

Comments

0

So much undefined behaviour in this program, the values printed are really quite immaterial.

1 Comment

How is it 7 people upvoted a -1 comment but the answer still has +1?
0

p is a pointer variable, which can store only address of a int variable. But you are storing 1000 as an address, which is invalid. And then you are storing 2000 to the variable q.

Now you are doing pointer arithmatic p-q. Always pointer arithmatic will gives the output based on the size of the type of address. Which will work like (p - q)/sizeof(type).

Consider if p and q are char * variable, then p-q will gives you the output as -1000

In your case p and q are int * variable, then p-q will gives you the output as 250 if size of int is 4 bytes. Execute this on the compiler where size of int is 2 bytes, you will get a result as -500.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.