给定
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/