c++ - 将 unsigned int 添加到 unsigned int*

标签 c++ c pointer-arithmetic unsigned-integer

我的开发环境由 ARM OMAP Sitata 的 g++ 交叉编译器组成。当将一个无符号 int 添加到一个无符号 int* 时,我发现了简单指针算术的一个不寻常的细微差别,如下所示:

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 所需的尽可能多的字节,即如果 int 则可能为 4 * n code> 是 32 位(在大多数正常架构上为 4 字节)。

这是标准的 C 行为。

关于c++ - 将 unsigned int 添加到 unsigned int*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42300621/

相关文章:

c - 变量不在数组中的指针算术

c++ - 内存分配运算符和表达式

c++ - 成员函数指针——只有一个地址?

c++ - while(getline(myReadFile, temp, ':' )) 执行一次迭代太多导致 vector 越界

c - 如何解决这个: two functions x = sin(x)/a

C 如何从命令行参数读取文件

c - Open() with O_WRONLY 会阻塞,即使我 open() with O_RDONLY 在另一端

C++奇怪的指针运算

c++ - 在 C/C++ 项目中查找 "undefined"引用

c - 不使用 * operator hack-y 方式获取产品