将 unsigned int 添加到 unsigned int*
adding unsigned int to unsigned int*
我的开发环境包括用于 ARM OMAP Sitata 的 g++ 交叉编译器。当将一个无符号整数添加到一个无符号整数 * 时,我发现了简单指针运算的一个不寻常的细微差别,如下所示:
unsigned int* dst_base_addr;
unsigned int* dst_addr;
unsigned int dst_offset;
只是试图将一个 (unsigned int) 添加到一个 (unsigned int*)
dst_addr = dst_base_addr + dst_offset;
上面的解释并不像人们天真地认为的那样,实际上产生了以下等效结果
dst_addr = (unsigned int*)((unsigned int)dst_base_addr + (dst_offset << 2));
补救的办法当然是如下进行适当的类型转换
dst_addr = (unsigned int*)((unsigned int)dst_base_addr + dst_offset);
问题:为什么在这种情况下甚至需要正确的类型转换?
The above is not interpreted as one might naively think but actually produces the following equivalent result
C(可能还有 C++)中的指针运算是以指向的对象的大小为单位完成的。如果将 n 添加到 int*
,生成的代码将添加表示 n int
s 所需的字节数,即如果 int
是 32 位(最多 4 个字节),则可能是 4 * n健全的架构)。
这是标准的 C 行为。
我的开发环境包括用于 ARM OMAP Sitata 的 g++ 交叉编译器。当将一个无符号整数添加到一个无符号整数 * 时,我发现了简单指针运算的一个不寻常的细微差别,如下所示:
unsigned int* dst_base_addr;
unsigned int* dst_addr;
unsigned int dst_offset;
只是试图将一个 (unsigned int) 添加到一个 (unsigned int*)
dst_addr = dst_base_addr + dst_offset;
上面的解释并不像人们天真地认为的那样,实际上产生了以下等效结果
dst_addr = (unsigned int*)((unsigned int)dst_base_addr + (dst_offset << 2));
补救的办法当然是如下进行适当的类型转换
dst_addr = (unsigned int*)((unsigned int)dst_base_addr + dst_offset);
问题:为什么在这种情况下甚至需要正确的类型转换?
The above is not interpreted as one might naively think but actually produces the following equivalent result
C(可能还有 C++)中的指针运算是以指向的对象的大小为单位完成的。如果将 n 添加到 int*
,生成的代码将添加表示 n int
s 所需的字节数,即如果 int
是 32 位(最多 4 个字节),则可能是 4 * n健全的架构)。
这是标准的 C 行为。