我有以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef union stateof stateof;
union stateof
{
stateof* foo;
double* bar;
};
typedef struct hunch hunch;
struct hunch{
double* first;
double* second;
};
void main(){
#define write(x) printf("%d \n",x);
int* storage = 0;
stateof* un = (stateof*)&storage;
un->foo = 300;
write(storage);
un->bar = 600;
write(storage);
hunch* h = (hunch*)&storage;
h->first = 1200;
write(storage);
h->second = 1600;
write(storage);
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出是:
300
600
1200
1200
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
当它们绝对不指向有效结构时,对于un->{foo,bar}和h->{first,second}语句执行意味着什么?在此期间究竟发生了什么,为什么联盟的输出与结构的输出不同?
您的程序会导致各种未定义的行为.你可以得到任何可以想象的输出.编译此代码时,您的编译器可能会给您各种警告 - 尝试修复这些警告,您应该朝着更好的方向前进.
假设您有一个正常的系统类型,您可以解释您获得输出的原因:
un->foo覆盖- 然后将其打印出来.storage300un->bar覆盖- 然后将其打印出来.storage600h->first覆盖- 然后将其打印出来.storage1200h->second(DANGEROUSLY)用值覆盖一些内存1600,然后再打印出来storage- 它仍然是1200.| 归档时间: |
|
| 查看次数: |
2493 次 |
| 最近记录: |