C++编程思想 第1卷 第3章 修改外部变量 指针传递

函数内的变量要改变函数外的变量,靠指针。

指针可以把函数外变量的地址传进来,函数就可以修改外部变量的地址


//: 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

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80603654
今日推荐