voidfunc(int n) { cout << "The value of n in func(): " << n << endl; cout << "The address of n in func(): " << &n << endl; n++; cout << "Then the value of n in func(): " << n << endl; }
intmain() { int n = 0; cout << "The value of n in main(): " << n << endl; cout << "The address of n in main(): " << &n << endl; func(n); cout << "Then the value of n in main(): " << n << endl; return0; }
voidfunc(int n) { printf("The value of n in func(): %d\n", n); printf("The address of n in func(): 0x%x\n", &n); n++; printf("Then the value of n in func(): %d\n", n); }
intmain() { int n = 0; printf("The value of n in main(): %d\n", n); printf("The address of n in main(): 0x%x\n", &n); func(n); printf("Then the value of n in main(): %d\n", n); return0; }
下边是可能的输出:
1 2 3 4 5 6
The value of n in main(): 0 The address of n in main(): 0x61fe1c The value of n in func(): 0 The address of n in func(): 0x61fdf0 Then the value of n in func(): 1 Then the value of n in main(): 0
第二行第四行说明,main() 中的实参 n 与 func() 中的形参 n 存储在内存的不同位置,不是同一个变量。第五第六行说明,对形参 n 的操作,不会影响实参 n。
voidfunc(int *p) { cout << "The value of n(*p) in func(): " << *p << endl; cout << "The address of n(p) in func(): " << p << endl; (*p)++; cout << "Then the value of n(*p) in func(): " << *p << endl; }
intmain() { int n = 0; cout << "The value of n in main(): " << n << endl; cout << "The address of n in main(): " << &n << endl; func(&n); // 把想要传递的参数的地址作为实参传入 cout << "Then the value of n in main(): " << n << endl; return0; }
voidfunc(int *p) { printf("The value of n(*p) in func(): %d\n", *p); printf("The address of n(p) in func(): 0x%x\n", p); (*p)++; printf("Then the value of n(*p) in func(): %d\n", *p); }
intmain() { int n = 0; printf("The value of n in main(): %d\n", n); printf("The address of n in main(): 0x%x\n", &n); func(&n); printf("Then the value of n in main(): %d\n", n); return0; }
下边是可能的输出:
1 2 3 4 5 6
The value of n in main(): 0 The address of n in main(): 0x61fe1c The value of n(*p) in func(): 0 The address of n(p) in func(): 0x61fe1c Then the value of n(*p) in func(): 1 Then the value of n in main(): 1
voidfunc(int &n2) { cout << "The value of n2 in func(): " << n2 << endl; cout << "The address of n2 in func(): " << &n2 << endl; n2++; cout << "Then the value of n2 in func(): " << n2 << endl; }
intmain() { int n1 = 0; cout << "The value of n1 in main(): " << n1 << endl; cout << "The address of n1 in main(): " << &n1 << endl; func(n1); cout << "Then the value of n1 in main(): " << n1 << endl; return0; }
下边是可能的输出:
1 2 3 4 5 6
The value of n1 in main(): 0 The address of n1 in main(): 0x61fe1c The value of n2 in func(): 0 The address of n2 in func(): 0x61fe1c Then the value of n2 in func(): 1 Then the value of n1 in main(): 1