C++ 指针类型的隐式转换

标签 c++ implicit-conversion pointer-conversion

考虑这种情况:

int *ptr;
int offset;
ptr = <some_address>;
offset = 10;

假设offset是32位变量。 ptr 的类型为 int*,目标架构为 64 位(因此 ptr 是 8 字节变量),offset 的类型为 int。计算表达式*(ptr + offset)的值时会进行什么转换?我在哪里可以阅读 2003 C++ 标准中的相关内容?

最佳答案

这就是标准对此 [expr.add]/4 的规定:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object84, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i ≠ n-th elements of the array object, provided they exist.

简单来说,这意味着当您写入 ptr + offset< 时,ptr 指向的地址会增加 offset * sizeof(*ptr)/.

关于C++ 指针类型的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095650/

相关文章:

c++ - 为什么重载赋值运算符会返回对类的引用?

char数组到uint8类型指针的转换

c++ - 别名和指针互换性

c++ - 如何在 Code::Blocks 中查看运行时调用的函数列表

c++ - 如何在 C++ 中创建强密码字符串?

c - Misra 和位操作

c# - 为什么不能在 C# 中将值隐式转换为字符串?

c# - int 的隐式运算符?

python - 如何从 C++ 返回 Python 类型的实例