在C++中,指针作为函数参数时,指针本身是按值传递的,这意味着函数内部会创建一个指针的副本,但这个副本仍然指向原始指针所指向的地址。因此,指针指向的地址在函数内外是相同的,但指针本身的地址(即指针变量的地址)在函数内外是不同的。
关键点
-
指针的地址:
-
指针本身是一个变量,它有自己的内存地址。
-
当指针作为参数传递时,函数内部会创建一个新的指针变量(副本),它的地址与原始指针不同。
-
-
指针指向的地址:
-
指针副本和原始指针指向的是同一个内存地址。
-
因此,通过指针修改目标变量的值会直接影响原始数据。
-
-
修改指针本身:
-
如果在函数内部修改指针(例如让它指向另一个地址),这种修改不会影响外部的原始指针,因为指针是按值传递的。
-
示例
#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
分析
-
指针本身的地址:
-
在
main
函数中,ptr
的地址是0x7ffee4b5c9f8
。 -
在
modifyPointer
函数中,ptr
的地址是0x7ffee4b5c9d8
,说明它们是不同的变量。
-
-
指针指向的地址:
-
在
main
函数和modifyPointer
函数中,ptr
都指向0x7ffee4b5c9f4
(即var
的地址)。
-
-
修改指针指向的值:
-
在
modifyPointer
函数中,通过*ptr = 100
修改了var
的值,因此在main
函数中var
的值变为100
。
-
-
修改指针本身:
-
在
modifyPointer
函数中,ptr
被修改为指向newVar
的地址,但这不会影响main
函数中的ptr
,因为指针是按值传递的。
-
总结
-
指针作为函数参数时,指向的地址在函数内外是相同的。
-
指针本身的地址在函数内外是不同的,因为指针是按值传递的。
-
如果需要修改指针本身(例如让它指向另一个地址),可以使用指针的引用或指针的指针。例如: