问题
If we have an array within a struct:
struct Names
{
uint8 fileId;
uint8 name[50];
};
and then we try to assign a uint16 from the array to a uint16 variable like:
uint16 someName = *((uint16 *)&NamesObj.name[21]);
Will this violate aliasing rule/alignment rules and lead to undefined behaviour?
回答1:
Yes, this violates C rules. The objects in name
are uint8
(presumably some unsigned 8-bit integer type), and they are accessed through a pointer to uint16
(presumably some 16-bit integer type).
The relevant part of the 2011 C standard, from draft N1570, is 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.
The type uint16
is none of these.
来源:https://stackoverflow.com/questions/48799736/does-aliasing-alignment-issues-occur-for-an-array-within-a-structure