简体   繁体   English

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

[英]C++ implicit conversion of pointer type

Consider this case: 考虑这种情况:

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

Assume that offset is 32-bit variable. 假设offset是32位变量。 ptr has type int* , the target architecture is 64-bit (so ptr is 8-byte variable), offset has type int . ptr具有int*类型,目标体系结构是64位(因此ptr是8字节变量), offset具有int类型。 What conversion will be performed when calculating value of expression *(ptr + offset) ? 计算表达式*(ptr + offset)值时将执行什么转换? Where can I read about it in the 2003 C++ standard? 在2003 C ++标准中,我在哪里可以读到它?

This is what the standard has to say about this [expr.add]/4: 这是标准对此[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. 如果指针操作数指向数组object84的元素,并且数组足够大,则结果指向与原始元素偏移的元素,以使结果数组元素和原始数组元素的下标之差等于整数表达式。 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. 换句话说,如果表达式P指向数组对象的第i个元素,则表达式(P)+ N(相当于N +(P))和(P)-N(其中N的值为n)表示分别存在于数组对象的第i + n个元素和第i =个第n个元素的情况下(前提是它们存在)。

In simpler words, this means that the address where ptr points to is incremented by offset * sizeof(*ptr) when you write ptr + offset . 用简单的话来说,这意味着当您写ptr + offset时, ptr指向的地址将增加offset * sizeof(*ptr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM