gpt4 book ai didi

c++删除指针然后访问它指向的值

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:58 24 4
gpt4 key购买 nike

我刚刚在 C++ 类中学习了指针和删除指针。我自己试过这段代码

# include<iostream>

using namespace std;

int main(){
int num = 10;
int *p = new int;

p = &num;
cout << *p << endl;
delete p;
cout << num << endl;
return 0;
}

删除指针后p , 我无法打印 num 的值.但是如果我删除 p在程序的最后,cout << num << endl;会给我 10。有人知道我跑到哪里了吗?

最佳答案

你先泄露了一个指针

int *p = new int;
p = &num; // You just leaked the above int

然后非法删除了一些你没有new

的东西
delete p;  // p points to num, which you did not new

关于c++删除指针然后访问它指向的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com