At about the time of 2/20/2007 10:11 PM, Praveen stated the following:
Hi,
I came across a program as follows
main()
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1-p2);
}
The output of the above program is 1.
Can some one explain me how it is 1.
Thanks in advance.
It's undefined behavior for reasons that others have pointed out.
In this case, x and y are placed ajacent in memory, so the difference is
1 since you are subtracting int pointers. Some people here have had -1
on their systems.
strata:/home/dr2867/c/test 1062 $$$ ->cat ub001.c
#include <stdio.h>
int main(void)
{
int x;
int y;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1 - p2);
printf("p1 = %0#x\np2 = %0#x\n", (unsigned int)p1, (unsigned int)p2);
return(0);
}
strata:/home/dr2867/c/test 1063 $$$ ->./compile ub001 ub001.c
Output File: ub001
Input Files:
ub001.c
gcc -W -Wall -Wshadow -Wpointer-arith -Wcast-align -Wstrict-prototypes
-Wnested-externs -Wwrite-strings -Wflo
at-equal -Winline -Wtrigraphs -ansi -std=c89 -pedantic -ggdb3 -o ub001
ub001.c
strata:/home/dr2867/c/test 1064 $$$ ->./ub001
1
p1 = 0xbfbfec34
p2 = 0xbfbfec30
strata:/home/dr2867/c/test 1065 $$$ ->
Look at the values of p1 and p2. They are 4 off, but it returns 1
because sizeof(int) is 4...at least on my system and apparently yours too.
--
Daniel Rudy
Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m
Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep