C++指针类型的隐式转换
C++ implicit conversion of pointer type
考虑这个案例:
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)
考虑这个案例:
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)