假设我有两个无符号的数字,每个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;

最佳答案

不能使用指向uint8_t的指针访问uint32_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/

10-11 20:54
查看更多