• 指针也是一种变量,作为函数形参和返回值的时候也是值拷贝(拷贝的是一个地址)
  • 使用指针引用的方式,代码更加简洁,逻辑更加清晰
  • 释放掉指针指向的空间后,一定记得把指针置空
  • 声明指针时就进行初始化或将其指向 NULL 是个好习惯

指针值拷贝:

void test(int * a){
    a = new int(20);
    //*a = 20;
    cout << "test point a = " << &a << endl;
    cout << "test:" << a << "\ta = " << *a << endl;
}
int main()
{
    int *a = new int(10);
    cout << "main point a = " << &a << endl;
    cout << "main:" << a << "\ta = " << *a << endl;
    test(a);
    cout << "main:" << a << "\ta = " << *a << endl;

    return 0;
}

输出:

Start
main point a = 0x7ffea2597be0
main:0x195d010	a = 10
test point a = 0x7ffea2597ba8
test:0x195e040	a = 20
main:0x195d010	a = 10
0
Finish
struct teacher{
    char name[64];
    int id;
};
// 方式一:
// 如果想要在函数内部实现指针内存分配
// 就只能用二级指针的形参
int getTT(struct teacher ** tpp){
    struct teacher *tp = (struct teacher *)malloc(sizeof(struct teacher));
    if(tp == NULL){
        return -1;
    }
    tp->id = 100;
    strcpy(tp->name, "zhang3");  
    *tpp = tp;
    
    return 0;
}
// 如果是想释放指针,也可以用一级指针
void freeTT(struct teacher **tpp){
    if(tpp == NULL){
        return;
    }
    if(*tpp != NULL){
        free(*tpp);
        *tpp = NULL;
    }
}
void freeTT(struct teacher *tpp){
    if(tpp == NULL){
        return;
    }
    if(tpp != NULL){
        free(tpp);
        // 此处的tpp是一个指针复本,置空没有效果
        // 所以只能在外部将指针置空
        tpp = NULL;
    }
}

// 方式二:
// 指针引用的方式,更加简洁
int getT(struct teacher *& tp){
    tp = (struct teacher *)malloc(sizeof(struct teacher));
    if(tp == NULL){
        return -1;
    }
    tp->id = 100;
    strcpy(tp->name, "zhang3");
    
    return 0;
}
void freeT(struct teacher *& tp){
    if(tp == NULL){
        return;
    }
    free(tp);
    tp = NULL;
}
int main()
{
    struct teacher *tp = NULL;
    // 1、利用二级指针
    //getTT(&tp);
    // 2、利用指针引用
    getT(tp);
    cout << tp->id << endl;
    cout << tp->name << endl;
    //freeTT(&tp);
    freeT(tp);
    cout << "==========================" << endl;
    if(tp == NULL){
        cout << "free ok" << endl;
        return 0;
    }
    cout << tp->id << endl;
    cout << tp->name << endl;
    return 0;
}

输出:

Start
100
zhang3
==========================
free ok
0
Finish