指针的引用

 C语言中的二级指针 

struct Teacher
{
    char name[64];
    int age;
};
//在被调用函数 获取资源
int getTeacher(Teacher **p)
{
    Teacher *tmp = NULL;
    if(p == NULL)
    {
        return -1;
    }
    tmp=(Teacher *)malloc(sizeof(Teacher));
    if(tmp == NULL)
    {
        return -2;
    }
    tmp->age = 33;
    // p是实参的地址 *实参的地址 
    *p = tmp;
    return 0;
}

 

 

C++中指针的引用 

int getTeacher2(Teacher*  &myp)
{
    //给myp赋值  相当于给main函数中的pT1赋值
    myp = (Teacher *)malloc(sizeof(Teacher));
    if(myp == NULL)
    {
        return -1;
    }
    myp->age = 34;

    return 0;
}

void FreeTeacher(Teacher *pT1)
{
    if(pT1 == NULL)
    {
        return ;
    }
    free(pT1);    
}

int main(void)
{
    Teacher *pT1 = NULL;
    
    //1 C语言中的二级指针
    getTeacher(&pT1);    
    cout << "age:"<<pT1->age<<endl;
    FreeTeacher(pT1);
    
    //2 C++中的引用  (指针的引用)
    //引用的本质 间接赋值后2个条件 让C++编译器帮我们程序员做了
    getTeacher2(pT1);
    cout << "age:"<<pT1->age<<endl;
    FreeTeacher(pT1);
    
    cout <<"hello..."<<endl;
    return 0;
}

运行结果:

 

posted @ 2018-09-22 20:44  Liu_Jing  Views(281)  Comments(0Edit  收藏  举报