1 引言
举个例子:在func
函数退出后,指针pInt
所指的内容*pInt
为 12
#include <stdio.h>
//公众号:C语言与CPP编程
int func(int* pRes)
{
if(pRes == NULL)
pRes = new int(12);//分配新的内存空间给指针pRes,并赋值
return 0;
}
int main ()
{
int *pInt = NULL;
int val = func(pInt);
printf("%d\n",*pInt); return 0;
}
解析:int func(int* pRes)
函数的形参是指针类型 int *pRes
,在函数体中 new
了一块内存并赋值 12,将内存地址赋值给指针 pRes
。在main
函数中,定义了指针pInt
,调用func
函数,把pInt
作为参数传入func
函数中。结果*pInt
并不是 12。
原