Thursday, August 2, 2007

Interesting C Program -14

Just see the output of the following C program. The output looks bit weird. Isnt it?


#include "stdio.h"
#define DPRINTF(x) printf("%s = %d\n",#x,x);

int main()
{
int x[20];
int *p,*q;
p=&x[5];
q=&x[9];
DPRINTF(p);
DPRINTF(q);
DPRINTF(q-p);
}



The output is


p = 2293580
q = 2293596
q-p = 4

q-p should be 16. But it gives 4. why?



The explanation goes like this.


Lets take a real life example.

Say you took 9 dozens of apples. You returned 5 dozens of apples. Then how many dozens of apples do you have? 4 dozens isnt it? You will not say 48 apples.

Similar is the case here. x[9] is stored in 2293596 address location and x[5] is stored in 2293580. p and q are integer pointers, each occupying 4 bytes. Now when you display the value of p and q, they will be 2293580 and 2293596 respectively. But if you ask for difference, it will be 4.
Inshort, 9 integer pointers - 5 integer pointers = 4 integer pointers.


Now just try this program:



#include "stdio.h"
#define DPRINTF(x) printf("%s = %d\n",#x,x);

int main()
{
int x[20],y,z;
int *p,*q;
p=&x[5];
q=&x[9];
DPRINTF(p);
DPRINTF(q);
DPRINTF(q-p);
y = p;
z = q;
DPRINTF(y);
DPRINTF(z);
DPRINTF(z-y);
}

The output is like this:

p = 2293580
q = 2293596
q-p = 4
y = 2293580
z = 2293596
z-y = 16


If you see the difference between z and y, you will get 16.

I think now no explanation is required now.

No comments:

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language