假设我有 2 个无符号数,每个 32 位,保存在一个数组中。第一个数字包含在位置 [0; 3] 和第二个位置 [4; 8].我现在要更改其中一个数字的值,下面的代码是否允许/有问题?
uint8_t array[8];
//...Fill it up...
uint32_t *ptr = NULL;
ptr = (uint32_t*)&array[0];
*ptr = 12345;
ptr = (uint32_t*)&array[4];
*ptr = 54321;
最佳答案
您不能使用指向 uint32_t
的指针访问 uint8_t
数组。这违反了 the strict aliasing rule (反之亦然——如果 uint8_t
是字符类型)。
相反,您可能想使用“type punning" 来规避 C(C99 及更高版本)类型系统。为此,您使用具有相应类型成员的union
:
union TypePunning {
uint32_t the_ints[2];
uint8_t the_bytes[2 * sizeof(uint32_t)];
}
// now e.g. write to the_bytes[1] and see the effect in the_ints[0].
// Beware of system endianness, though!
关于c - 使用 uint32_t* 更改 uint8_t 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39388889/