i have asked this question in a written test. while running the below code on my lapi, i am getting 10 as output
#include<stdio.h>
int main()
{
int *i, *j;/* two pointer variable*/
i = (int *)60;
j = (int *)20;
printf("%d \n",i-j);
return 0;
}
Output :
10
Can anyone tell me why the output is 10
.
According to the C Standard (6.5.6 Additive operators)
9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
So your program has undefined behaviour because the pointers do not point to elements of the same array.
Nevertheles it seems that the compiler simply generates an object code for subtracting two pointers irrespective of whether the pointers point to elements of the same array (it trusts you).
In this case the difference between the two pointers according to the pointer arithmetic is the number of elements that can be placed in the memory between two pointers.
In your case the sizeof( int )
is equal to 4
. So a memory that has size of 40 bytes can accomodate 10
elements of type int provided that sizeof( int )
is equal to 4
.
This value that is 10 is outputed by the printf function.