您的位置:首页 > 其它

指针作为函数参数的情形

2008-02-27 14:22 225 查看
1. 形参在函数结束后释放。所以对形参的赋值不起作用。而实参为空

#include <iostream.h>

void func(int** ptr)
{
 int* p  = new int(66);
 cout<<ptr<<endl;                                         // ptr is 0x00000000
 ptr = &p;
 cout<<ptr<<endl;                                        // ptr is 0x0012ff1c
 
}

int main()
{
     int** np = NULL;
 func(np);
  cout<<np<<endl;                                      // ptr is 0x00000000
 return 0;


2.形参指向的指针分配了内存,函数结束后形参释放。形参指向的指针没有变化

void func(int** ptr)
{
 int* p  = new int(66);
 cout<<ptr<<endl;
 *ptr = p;
 cout<<ptr<<endl;
 
}

int main()
{
 int* p = NULL;
    int** np = &p;
 func(np);
 
 cout<<*p<<endl;
 cout<<**np<<endl;
 
 return 0;
}

输出 66,66

注意分别形参本身和形参所指向的对象之间的差别
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null c