Raja G
Raja G

Reputation: 6633

C question with pointers

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?

Upvotes: 0

Views: 573

Answers (4)

rashok
rashok

Reputation: 13414

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.

Upvotes: 0

kevin cline
kevin cline

Reputation: 2736

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); 
}

Upvotes: 12

Roland Rabien
Roland Rabien

Reputation: 8836

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.

Upvotes: 6

Puppy
Puppy

Reputation: 146910

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

Upvotes: 0

Related Questions