c - offsetof 在检查 union 成员的字节偏移量时返回 0

标签 c

<分区>

如标题所示,我想从该成员之前的其他成员获取 union 成员的偏移量(以字节为单位)(使用 offsetof 中定义的 stddef.h 宏)。这适用于预期的结构

#include <stdio.h>
#include <stddef.h>

struct bio {
  int age;
  char name;
};


int main( void ) {
  printf("%d\n", offsetof(struct bio, name));  // result is 4 , which is what i expected
}

但对于 union 它打印 0

#include <stdio.h>
#include <stddef.h>

union bio {
  int age;
  char name;
};


int main( void ) {
  printf("%d\n", offsetof(union bio, name)); // 0
}

只是一个后续问题,这种行为的原因是因为 union 的成员存储在同一个内存块中?

作为这个解释的一部分 wikipedia offsetof我还希望得到 4 而不是 0 的值

最佳答案

在 union 中,分配的空间是 union 本身中每个字段所需的最大字节数。所以对于 bio(假设 sizeof(int)=4):

sizeof(bio) = max(sizeof(int), sizeof(char)) = sizeof(4, 1) = 4

这是因为所有 union 字段共享相同的内存空间,该内存空间从 union 本身的开头开始。

bio.age = 24
bio.name = 'a' //a will use the first byte in the union, just like the first byte of the integer

您也可以通过打印指针来检查它。

关于c - offsetof 在检查 union 成员的字节偏移量时返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54625547/

相关文章:

c - 如何在 C 中检测/分析内存(堆、指针)读写?

c - 如何在多行中编写#pragma openmp?

c - 多线程和 CPU 缓存

通过 C 中的数组自定义迭代打印每个第 n 个值

c - 如何在 printf(C 语言)中使用系统 ("date")?

c - 在 C 程序中使用 SQLite3 - 简单的设置问题

c - malloc 如何在多线程环境中工作?

c - 根据其值打印#define 的名称?

c - do-while 循环没有结束

c - 如何从 20 个样本中找到正弦波的幅度和频率?