考虑这种情况:
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/