在阅读一些C/C++源代码的时候不太理解给函数传递指针的指针的用法,在做了一些思考之后整理如下:
以下面的代码片段为例讨论指针形参的作用:
struct Temp {
int i;
double d;
};
void test(Temp *para)
{
para->i = 200;
para->d = 300.00;
//在函数内部申请的Temp结构体要怎么传递出去呢?
Temp *k = new Temp;
k->i = 100;
k->d = 200.0;//这里的内存泄漏仅是在该进程运行时,之后系统会回收这些资源
}
int main()
{
Temp *pt = new Temp;
pt->d = 200.00;
pt->i = 100;
cout << "before test:" << pt->i << " " << pt->d << endl;
test(pt);
cout << "after test:" << pt->i << " " << pt->d << endl;
}
以下面的代码片段为例讨论指针的指针形参的作用:
struct Temp {
int i;
double d;
};
void test(Temp **para)
{
Temp *k = new Temp;
k->i = 100;
k->d = 200.0;
*para = k;
}
int main()
{
Temp *pt = new Temp;
pt->d = 1000.00;
pt->i = 500;
cout << "before test:" << pt->i << " " << pt->d << endl;
test(&pt);
cout << "after test:" << pt->i << " " << pt->d << endl;
}