指针的引用 *&

函数的参数使用指针的引用,可以在函数中修改传入的指针的指向;

如下代码:

#include <iostream> 
// 普通指针参数
void modifyPointerValue(int* ptr) {
    int newValue = 10;
    ptr = &newValue; // 修改指针本身,不会影响外部的原始指针
}

// 指针引用参数
void dangling_modifyPointerReference(int*& ptr) {
    int newValue = 0;   // 局部变量被销毁,产生了悬空指针
    ptr = &newValue; // 修改指针本身,会影响外部的原始指针
}
// 指针引用参数
void modifyPointerReference(int*& ptr) {
    int *newValue = new int(0);
    ptr = newValue; // 修改指针本身,会影响外部的原始指针
}
int main() {
    int value = 5;
    int* ptr = &value;
  
    std::cout << "Before modifyPointerValue: " << *ptr << std::endl;
    std::cout << "Before modifyPointerValue ptr: " << ptr << std::endl;
    modifyPointerValue(ptr);
    std::cout << "After modifyPointerValue: " << *ptr << std::endl;
    std::cout << "After modifyPointerValue ptr: " << ptr << std::endl;

    std::cout << "Before modifyPointerReference: " << *ptr << std::endl;
    std::cout << "Before modifyPointerReference ptr: " << ptr << std::endl;
    modifyPointerReference(ptr);
    std::cout << "After modifyPointerReference: " << *ptr << std::endl;
    std::cout << "After modifyPointerReference ptr: " << ptr << std::endl;

    return 0;
}

其中有一个错误,dangling_modifyPointerReference函数中产生了悬空指针,因为newValue只是一个局部变量,退出函数的时候,指针指向的内容已经没有了,需要在栈上创建一个变量,避免悬空指针的产生;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值