C++之指针作为函数参数

        在C++中,指针作为函数参数时,指针本身是按值传递的,这意味着函数内部会创建一个指针的副本,但这个副本仍然指向原始指针所指向的地址。因此,指针指向的地址在函数内外是相同的,但指针本身的地址(即指针变量的地址)在函数内外是不同的。

关键点

  1. 指针的地址

    • 指针本身是一个变量,它有自己的内存地址。

    • 当指针作为参数传递时,函数内部会创建一个新的指针变量(副本),它的地址与原始指针不同。

  2. 指针指向的地址

    • 指针副本和原始指针指向的是同一个内存地址。

    • 因此,通过指针修改目标变量的值会直接影响原始数据。

  3. 修改指针本身

    • 如果在函数内部修改指针(例如让它指向另一个地址),这种修改不会影响外部的原始指针,因为指针是按值传递的。

示例

#include <iostream>
using namespace std;

void modifyPointer(int* ptr) {
    cout << "Inside function - Address of ptr (pointer itself): " << &ptr << endl;
    cout << "Inside function - Address pointed by ptr: " << ptr << endl;

    // 修改指针指向的值
    *ptr = 100;

    // 尝试修改指针本身(让它指向另一个地址)
    int newVar = 200;
    ptr = &newVar;
    cout << "Inside function - After modification, address pointed by ptr: " << ptr << endl;
}

int main() {
    int var = 10;
    int* ptr = &var;

    cout << "Outside function - Address of ptr (pointer itself): " << &ptr << endl;
    cout << "Outside function - Address pointed by ptr: " << ptr << endl;

    modifyPointer(ptr);

    cout << "Outside function - Value of var after modification: " << var << endl;
    cout << "Outside function - Address pointed by ptr after function call: " << ptr << endl;

    return 0;
}

        输出结果

Outside function - Address of ptr (pointer itself): 0x7ffee4b5c9f8
Outside function - Address pointed by ptr: 0x7ffee4b5c9f4
Inside function - Address of ptr (pointer itself): 0x7ffee4b5c9d8
Inside function - Address pointed by ptr: 0x7ffee4b5c9f4
Inside function - After modification, address pointed by ptr: 0x7ffee4b5c9d4
Outside function - Value of var after modification: 100
Outside function - Address pointed by ptr after function call: 0x7ffee4b5c9f4

分析 

  1. 指针本身的地址

    • main函数中,ptr的地址是0x7ffee4b5c9f8

    • modifyPointer函数中,ptr的地址是0x7ffee4b5c9d8,说明它们是不同的变量。

  2. 指针指向的地址

    • main函数和modifyPointer函数中,ptr都指向0x7ffee4b5c9f4(即var的地址)。

  3. 修改指针指向的值

    • modifyPointer函数中,通过*ptr = 100修改了var的值,因此在main函数中var的值变为100

  4. 修改指针本身

    • modifyPointer函数中,ptr被修改为指向newVar的地址,但这不会影响main函数中的ptr,因为指针是按值传递的。

总结

  • 指针作为函数参数时,指向的地址在函数内外是相同的

  • 指针本身的地址在函数内外是不同的,因为指针是按值传递的。

  • 如果需要修改指针本身(例如让它指向另一个地址),可以使用指针的引用指针的指针。例如:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值