c++ - Structure memory layout In C -



c++ - Structure memory layout In C -

struct fraction { int num; int denum; } pi; pi.num=22; pi.denum=7; ((fraction*)&(pi.denum))->num=12; cout << endl; cout << pi.denum <<endl; cout << pi.num <<endl;

i can understand memory diagram till point have confusion is next code

((fraction*)&pi.denum)->denum=33;

is there legal way 33 printed out ?? command value stored not in view of object?

a struct fraction layed out in memory 2 consecutive ints. code looks @ look &pi.denum, address of sec integer:

----------------------- | int num | int denum | ----------------------- ^ ^ | | &pi &(pi.denum)

but cast &pi.denum fraction * , seek access ((fraction*)&(pi.denum))->num. since num first fellow member of struct fraction, c standard guarantees address same struct itself.

&(((fraction*)&(pi.denum))->num) == (fraction*)&(pi.denum) == &pi.denum.

it is valid memory location - luck. if tried access ((fraction*)&(pi.denum))->denom, you'd undefined behavior - perchance corrupting memory or causing segmentation fault.

bottom line, ((fraction*)&(pi.denum))->num = 12 nonsense code. never useful.

c++ memory pointers struct

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -