c - Storing Pointers difference in integers? -
this code:
#include<stdio.h> #include<conio.h> int main() { int *p1,*p2; int m=2,n=3; m=p2-p1; printf("\np2=%u",p2); printf("\np1=%u",p1); printf("\nm=%d",m); getch(); return 0; }
this gives output as:
p2= 2686792 p1= 1993645620 m= -497739707
i have 2 doubts code , output:
since 'm' int, shouldn't take p2-p1 input since p1 , p2 both pointers , m integer should give error "invalid conversion 'int' 'int' " isn't. why?
even after takes input, difference isn't valid. why it?
since 'm' int, shouldn't take p2-p1 input since p1 , p2 both pointers , m integer should give error "invalid conversion 'int' 'int' " isn't. why?
this type of error or warning depends on compiler using. c compilers times give programmers plenty of rope hang with...
even after takes input, difference isn't valid. why it?
actually, difference correct! using pointer arithmetic perform calculation. example..
p2= 2686792
p1= 1993645620
since pointers not initialized, assigned garbage values ones above. now, want perform operation p2 - p1, i.e. asking memory address comes p1 memory blocks before p2. since p1 , p2 pointers integers, size of memory block sizeof(int)
(almost 4 bytes). therefore:
p2 - p1 = (2686792 - 1993645620) / sizeof(int)
= (2686792 - 1993645620) / 4 = -497739707
Comments
Post a Comment