I found this code sample in a book, but I am unable to understand the expression in printf statement. and this program compiles successfully giving output as 4. kindly advise...
void main(){
unsigned char c;
typedef struct name {
long a;
int b;
long c;
}r;
r re = {3,4,5};
r *na=&re;
printf("%d",*(int*)((char*)na + (unsigned int ) & (((struct name *)NULL)->b)));
}
Lets start from the last line:
Lets interpret:
Is actually casting
& (( (struct name *)NULL)->b )
into aunsigned int
.& (( (struct name *)NULL)->b )
is the address (i.e it gives a pointer to):Which is actually the offset of
b
(asname.b
) from NULL (0), which is 4 bytes (assuming along
is 4 bytes) and converted to a pointer of int, gives you 2 (assumingint
is 2 bytes).If instead of
NULL
it would have been a pointer to0xFFFF0000
, then&(ptr->b)
would have been0xFFFF0002
. But it more like&(0 -> b)
so its0x00000002
.So,
(unsigned int ) & (( (struct name *)NULL)->b ) == 2
(or maybe 1, or maybe 4, depending on the machine).The rest is simple:
*(int*)((char*)na + 2
will point tore->b
. So it should print 4 (what have been initialized in the code,r re ={3,4,5};
).P.S: even if
(unsigned int ) & (( (struct name *)NULL)->b ) != 2
(maybe it's 1, 4 or 8) - it should still print 4 because it then uses the same offset to get the value.