C指针转换规则

fth*_*ker 1 c pointers unions

我有以下代码:

#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}语句执行意味着什么?在此期间究竟发生了什么,为什么联盟的输出与结构的输出不同?

Car*_*rum 7

您的程序会导致各种未定义的行为.你可以得到任何可以想象的输出.编译此代码时,您的编译器可能会给您各种警告 - 尝试修复这些警告,您应该朝着更好的方向前进.

假设您有一个正常的系统类型,您可以解释您获得输出的原因:

  1. 使用值修改un->foo覆盖- 然后将其打印出来.storage300
  2. 使用值修改un->bar覆盖- 然后将其打印出来.storage600
  3. 使用值修改h->first覆盖- 然后将其打印出来.storage1200
  4. 修改h->second(DANGEROUSLY)用值覆盖一些内存1600,然后再打印出来storage- 它仍然是1200.