我很困惑與代碼塊:指針C++解釋
ipPtr = ipPtr + 3; // 5
cout << *ipPtr << endl;
爲什麼cout
不是5,但一些隨機的大量?任何人都可以向我解釋一下。據我的理解,我認爲cout << *ipPtr << endl;
指向它上面的*ipPtr
。我對嗎 ?
#include <iostream>
void main(){
using namespace std;
int iaArray[] = {1,2,3,4,5};
int* ipPtr = 0;
ipPtr = &(iaArray[1]);
cout << *ipPtr << endl;//2
++ipPtr;
cout << *ipPtr << endl;//3
ipPtr = ipPtr + 3; //not 5 but random number.
cout << *ipPtr << endl;
}
您指向數組的末尾之外。數組的大小是5,而你指向的是第6個元素,這就是你得到一些隨機數的原因。 2 + 1 + 3 = 6不是5 :) –
你有機會接受其中一個答案嗎? –