Given below is the code. Can someone explain the logic behind it.
#include<stdio.h>
int main()
{
int *i,*j;
i=(int *)60;
j=(int *)20;
printf("%d",i-j);
return 0;
}
Given below is the code. Can someone explain the logic behind it.
#include<stdio.h>
int main()
{
int *i,*j;
i=(int *)60;
j=(int *)20;
printf("%d",i-j);
return 0;
}
You're assigning the pointers values of 60 and 20.
Since int*
(pointers), on your platform are 4 bytes each (32bit), and there is a difference of 40 bytes between j and i, i-j
returns 40 / sizeof(int)
, which prints 10
.
It's because of the pointer arithmetic.
When you add some value to a pointer, the result will depend of the type of the pointer. On your system, sizeof(int)
seems to be equal to 4 bytes, so when you do :
int *p = 0x1000; //totally dumb value, just for example
printf("%p\n", p + 1);
This will print 0x1004.
So : (int*)60 - (int*)20 = 10, because 10 * 4 (the size of int
on your system).
Distance between two pointers of type T
is calculated nearly as (a - b) / sizeof (T)
. If you say
int* a = 0xdeadbeef;
int* b = a + 1;
then numeric distance between a and b will be sizeof(int) (generally 4) but not 1. And in case
char* x = 0x12345678;
char* y = x + 1;
distance will be exactly 1.
i and j are pointers to int
s. On a 4 byte machine, int
s are 4 bytes long, and the difference between the pointer 2 to consecutive int
s will be 4. 60 - 20 / 4
is - err - 10
Well i guess you got an answer but here is the title; you have to consider the size of the variable, which means, in this case that sizeof(int)==4. so 40 bytes equal to 10 int's(in your operation system).
60-20 => 40 bytes.
sizeof(int *) = 4 bytes.
i => int *; j=int*
So, when you do 60-20, you are doing (int * - int *) i.e. how many int * are in 60-20?
60-20 = 40
40/4 => 10.
NOTE: assumption is that sizeof(int *) is 4 bytes.