函数内的变量要改变函数外的变量,靠指针。
指针可以把函数外变量的地址传进来,函数就可以修改外部变量的地址
//: C03:PassAddress.cpp // From Thinking in C++, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 2000 // Copyright notice in Copyright.txt #include <iostream> using namespace std; void f(int* p) { cout << "p = " << p << endl; cout << "*p = " << *p << endl; *p = 5; cout << "p = " << p << endl; } int main() { int x = 47; cout << "x = " << x << endl; cout << "&x = " << &x << endl; f(&x); cout << "x = " << x << endl; getchar(); } ///:~
外部变量已经改变了
指针最常见的是修改外部的变量
输出
x = 47
&x = 00AFF9C4
p = 00AFF9C4
*p = 47
p = 00AFF9C4
x = 5