c - 使用 uint32_t* 更改 uint8_t 数组的值

标签 c pointers memory

假设我有 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/

相关文章:

C++ 问题 :After assigning value to a variable, 另一个变量改变了

c - 指向 volatile 字符的 volatile 指针。额外的静态关键字

c - 我无法在从函数返回的 char 指针上使用 free()

python - Google Cloud IoT 网关连接内存不足

c - 有效地从 CSV 中读取特定行,C

c - 如何将asin结果保存在短变量中?

c - 奇怪的 GCC short int 转换警告

c - 如何使 pthreads 池运行任意例程

arrays - 具有 O(1) 插入和删除的双向链表的紧凑多数组实现

python - 如何实现-在__del__上写入文件?