我很困惑与代码块:指针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 :) –
你有机会接受其中一个答案吗? –