c语言的二级指针与指针的引用

1.首先一点,引用不是对象,所以不会有内存,故此不存在指向引用的指针

2.二级指针可以作为形参在被调用函数中获取资源,看下面的代码

#include<iostream>
using namespace std;
struct people//定义一个people结构体
{
	char name[100];
	int age;
};
void pr(people **p)//通过二级指针来让main函数中的一个指向people的变量获得age的资源
{
	people *p1 = NULL;
	p1 = (people*)malloc(sizeof(people));
	p1->age = 15;//指针用->来访问
	*p = p1; 
}
void fre(people *p)
{
	if (p != NULL)
	{
		free(p);
	}
}
void main()
{
	people *p = NULL;
	pr(&p);
	cout << p->age << endl;//
	fre(p);
	system("pause");
}

3.用指针的引用来实现

#include<iostream>
using namespace std;
struct people//定义一个people结构体
{
	char name[100];
	int age;
};
void pr(people *&p)//从右向左看,第一个运算符对p的影响最大int 
{
	p = (people*)malloc(sizeof(people));
	p->age = 15;
}

void fre(people *p)
{
	if (p != NULL)
		free(p);
}
void main()
{
	people *p = NULL;
	pr(p);
	
	cout << p->age << endl;
	fre(p);
	system("pause");
}

这2种方法建议使用指针的引用。

猜你喜欢

转载自blog.csdn.net/qq_43702629/article/details/89366488