c - 指向 union 的指针是否需要为所有成员对齐

标签 c alignment unions

给定

typedef union { unsigned char b; long l; } BYTE_OR_LONG;

有一个函数是否合法

unsigned long get_byte_or_long(BYTE_OR_LONG *it)
{
  if (it->b)
    return it->b;
  else
    return decode_long(it->l); // Platform-dependent method
                               // Could return (it), (it>>8), etc.
}

并调用它

void test()
{
  long l = encode_long(12345678);  // Platform-dependent; could return
                                   // (it<<8), (it & 16777215), etc.
  char b[2] = {12,34};
  BYTE_OR_LONG *bl[3];
  bl[0] = (BYTE_OR_LONG*)&l;
  bl[1] = (BYTE_OR_LONG*)b;
  bl[2] = (BYTE_OR_LONG*)(b+1);
  for (int i=0; i<3; i++)
    printf("%lu\n", get_byte_or_long(bl[i]));
}

当然构造一个未对齐的 BYTE_OR_LONG *p 然后访问 p->l 将是未定义的行为。此外,即使将未对齐的指针转换为 (unsigned long*) 的行为也将是未定义的行为,因为实现可能不需要像 char*< 这样的类型那么多的位。然而,对于 union 来说,事情似乎还不清楚。

据我了解,指向 union 的指针应该等同于指向其任何元素的指针。这是否意味着保证指向 union 类型的指针的实现必须能够识别其中包含的任何类型的任何实例[因此 BYTE_OR_LONG* 必须能够识别任何 unsigned char],还是只需要程序员将满足其中每个成分的每个对齐要求的 union 类型指针转换为指针?

最佳答案

Does that mean that implementations required to guarantee that a pointer to a union type must be capable of identifying any instance of any type contained therein ... ?

长问短答:是的。

(稍后我会挖掘标准引用)

基本上这是因为结构/union 的第一个元素保证在它之前没有填充。

关于c - 指向 union 的指针是否需要为所有成员对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28968873/

相关文章:

c++ - 使用 C 中的 Lua API 覆盖内置类型的运算符

编译所有 C 文件并使用 Makefile 创建可执行文件

css ,重新调整内联元素的大小以适应 block 宽度

c++ - union 像类/结构一样使用

c - 通过网络连接发送 C 中 union 的内容

c - K&R 中的示例在其函数之外访问局部变量?

c - 文件段错误(核心转储)(C-linux)

html - 如何开始一个新行并将换行符与 flexbox 中的另一个元素对齐?

css - 导航栏行未垂直对齐

c++ - 检查 union 平等