结构中的数组是否会出现 Aliasing/Alignment 问题?
Does Aliasing/Alignment issues occur for an Array within a Structure?
如果我们在结构中有一个数组:
struct Names
{
uint8 fileId;
uint8 name[50];
};
然后我们尝试将数组中的 uint16 分配给 uint16 变量,例如:
uint16 someName = *((uint16 *)&NamesObj.name[21]);
这会违反别名 rule/alignment 规则并导致未定义的行为吗?
是的,这违反了 C 规则。 name
中的对象是 uint8
(大概是一些无符号的 8 位整数类型),它们通过指向 uint16
(大概是一些 16 位整数类型)的指针访问。
2011 C 标准的相关部分,来自 N1570 草案,是 6.5 7:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
类型 uint16
是其中的 none 个。
如果我们在结构中有一个数组:
struct Names
{
uint8 fileId;
uint8 name[50];
};
然后我们尝试将数组中的 uint16 分配给 uint16 变量,例如:
uint16 someName = *((uint16 *)&NamesObj.name[21]);
这会违反别名 rule/alignment 规则并导致未定义的行为吗?
是的,这违反了 C 规则。 name
中的对象是 uint8
(大概是一些无符号的 8 位整数类型),它们通过指向 uint16
(大概是一些 16 位整数类型)的指针访问。
2011 C 标准的相关部分,来自 N1570 草案,是 6.5 7:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
类型 uint16
是其中的 none 个。