C指针转换规则

标签 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);
}

这个程序的输出是:

300   
600   
1200   
1200

这里发生了什么?

un->{foo,bar}h->{first,second} 语句在绝对不指向时执行是什么意思到有效的结构?在此期间究竟发生了什么,为什么 union 的输出与结构的输出不同?

最佳答案

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

假设你有一个普通的系统,你得到你看到的输出的原因可以解释为:

  1. 修改 un->foo 会用值 300 覆盖 storage - 然后打印出来。
  2. 修改 un->bar 会用值 600 覆盖 storage - 然后打印出来。
  3. 修改 h->first 用值 1200 覆盖 storage - 然后打印出来。
  4. 修改 h->second(危险)用值 1600 覆盖一些内存,然后您再次打印出 storage - 它仍然是 1200

关于C指针转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447755/

相关文章:

c++ - 在 Arduino 中制作更好的循环

c - 我怎样才能在c中创建一个n维数组

c - 不在 C 中转换指针会导致问题吗?

C指针错误值?

c++ - C++ union 的性能影响

c++ - 布局兼容类型的 union

c++ - CUDA 中不同 block 和线程的性能优化

c - 读取一串预期模式

struct 和 volatile int 的 C- union- struct 的更新也是 volatile 的吗?

使用 malloc 和 realloc 将静态数组更改为动态数组?