结构存储器布局在C中 [英] Structure memory layout In C

查看:149
本文介绍了结构存储器布局在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 the memory diagram till this point What I have confusion is is the following code

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

有没有合法的方式让33打印出来?
ANY命令获取不在对象视图中存储的值

Is there a legal way to get that 33 printed out ?? ANY command to get the value stored which is not in the view of an object?

推荐答案

A struct fraction 将作为两个连续的 ints 在内存中展开。您的代码查看表达式& pi.denum ,它是第二个整数的地址:

A struct fraction will be layed out in memory as two consecutive ints. Your code looks at the expression &pi.denum, which is the address of the second integer:

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

c>< / c $ c>到 fraction * ,并尝试访问((fraction *)& .denum)) - > num 。由于 num struct fraction 的第一个成员,C标准保证其地址与struct本身相同。

But you cast &pi.denum to a fraction * and try to access ((fraction*)&(pi.denum))->num. Since num is the first member of struct fraction, the C standard guarantees that its address is the same as the struct itself. So

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

有效的内存位置 - 如果您尝试访问((fraction *)&(pi.denum)) - > denom ,您会得到未定义的行为 - 可能会破坏内存或导致细分

It is a valid memory location - but only by luck. If you tried to access ((fraction*)&(pi.denum))->denom, you'd get undefined behavior - possibly corrupting memory or causing a segmentation fault.

底线,((fraction *)&(pi.denum)) - " num = 12 是无意义代码。它永远不会做任何有用的。

Bottom line, ((fraction*)&(pi.denum))->num = 12 is nonsense code. It could never do anything useful.

这篇关于结构存储器布局在C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆