为什么当我递增指针然后取消引用它时,我得到一个随机数?
这是我的代码:
#includeusing namespace std; int main(){ int reference = 10; int *health = &reference; int *health1 = health; cout << "Health Address: " << health << "\nHealth1 Address: " << health1 << "\nReference Address: " << &reference << endl; health1++; cout << "Health1 value after being incremented then dereferenced: " << *health1 << endl; }
我的输出是:
健康地址:0x7fff5e930a9c
Health1地址:0x7fff5e930a9c
参考地址:0x7fff5e930a9c.
增加后的Health1值然后取消引用:197262882
我期望获得0,因为下一个内存地址的下一个值将为null,但在这种情况下情况并非如此.
由于内存中的下一个位置为空,我原本期望得到0,但在这种情况下情况并非如此.
你的期望是错误的.增加指针后,它不再指向有效的内存缓冲区.取消引用它会调用未定义的行为.