typecasting in c between data types
I wrote this small code to test my understanding. But dint understand some
facts behind it. I am working on a 64 bit little endian machine. So any
pointer is 8 bytes. That means
#include<stdio.h>
int main(){
char *c = (char *)0x12345678889;
long a = 1;
int b = (long)(c-a);
/* int cc = (int)(c-a); gives compiler error */
printf("val = %x and b = %x", c-a,b);
return 0;
}
Output
val = 45678888 and b = 45678888
Say the starting address is 100. So the char* would be stored in memory as
100->89, 101->88 ... 105->12 and bytes 106 and 107 will be unused. Is this
assumption of mine correct in the first place? Since int and long are 4
bytes in a 64 bit machine, it will start from 100,101,102 and 103 and will
consider only these bytes. So 45678889 - 1 = 45678888. Is my understanding
correct? Finally, I dont understand while the commented line gives a
compiler error. The compiler had implicitly typecasted the above line. But
why not below?
Thanks
Chid
No comments:
Post a Comment