C struct 的内存布局

0 c struct

我可以确定以下代码适用于所有平台吗?

struct example{
  int a;
  int b;
} example;

*((int*)(((void*)&example) + sizeof(int))) = 33;
Run Code Online (Sandbox Code Playgroud)

这应该将 (b) inside (example) 的值更改为 33。

P__*_*J__ 5

肯定不会。

&example + sizeof(int)此操作将指针sizeof(int) * sizeof(example)字节向前移动。

而这一行根本不会编译

*(&example + sizeof(int)) = 33;

要知道结构中特定字段的偏移量或联合中使用offsetof

http://man7.org/linux/man-pages/man3/offsetof.3.html