指针的赋值的问题

前提 :

在写树的时候,发现一个关于指针的问题,想了一会才想到为什么,记录

问题:

用指针n让p指向一个内存

#include <iostream>
using namespace std;
int main()
{
	int* p = NULL;
	int* n = p;
	n = new int(4);
	delete n;
	system("pause");
	return 0;
}

分析:

1.int* p = NULL; int* n = p;
在这里插入图片描述
2. n = new int(4);
在这里插入图片描述

明显错误
正确方式应该是n存入p的地址,然后进行赋值

修改:

#include <iostream>
using namespace std;
int main()
{
	int* p = NULL;
	int** n = &p;
	(*n) = new int(4);
	delete n;
	system("pause");
	return 0;
}

图示:

  1. int* p = NULL; int** n = &p;
    在这里插入图片描述

  2. (*n) = new int(4);
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zbbzb/article/details/82977041