删除后的 C++ 指针然后赋值
C++ Pointer after delete it then give value
我遇到了这个问题,它创建了3块内存,如果删除*r我很困惑,**r是否还存在?我应该将 **r 移动到 *r 的位置吗?
我需要另一个 "new int" 语句来提供价值吗?
int t = 5;
int **r;
r = new int *; //declare pointer
*r = new int;
delete *r; // delete pointer
*r = t; //give new value
抱歉提问有误。还在里面学习。谢谢。
您的代码正确 (Ideone):
#include <iostream>
using namespace std;
int main() {
int **r = new int *; // declare pointer to int*
cout << r << endl; // outputs some address in memory (pointer to int*)
cout << *r << endl; // outputs some garbage value
// cout << **r << endl; // it's invalid
*r = new int; // assign to memory pointed by r new value
cout << *r << endl; // outputs some address in memory (pointer to int)
cout << **r << endl; // outputs some garbage value
delete *r; // delete pointer to int
cout << *r << endl; // outputs same address in memory, but we can't dereference it
// cout << **r << endl; // it's invalid, because we deleted *r
// here you can acces r, *r, but not
return 0;
}
我遇到了这个问题,它创建了3块内存,如果删除*r我很困惑,**r是否还存在?我应该将 **r 移动到 *r 的位置吗? 我需要另一个 "new int" 语句来提供价值吗?
int t = 5;
int **r;
r = new int *; //declare pointer
*r = new int;
delete *r; // delete pointer
*r = t; //give new value
抱歉提问有误。还在里面学习。谢谢。
您的代码正确 (Ideone):
#include <iostream>
using namespace std;
int main() {
int **r = new int *; // declare pointer to int*
cout << r << endl; // outputs some address in memory (pointer to int*)
cout << *r << endl; // outputs some garbage value
// cout << **r << endl; // it's invalid
*r = new int; // assign to memory pointed by r new value
cout << *r << endl; // outputs some address in memory (pointer to int)
cout << **r << endl; // outputs some garbage value
delete *r; // delete pointer to int
cout << *r << endl; // outputs same address in memory, but we can't dereference it
// cout << **r << endl; // it's invalid, because we deleted *r
// here you can acces r, *r, but not
return 0;
}