函数参数传递的只能是数值,所以当指针作为函数参数传递时,传递的是指针的值,而不是地址。
相关阅读:c指针作为参数传递以及指针的指针
测试代码1:
#include <iostream>
using namespace std;
void test(int* p) {
p = new int;
*p = 2;
}
void test2(int** p) {
*p = new int;
**p = 2;
}
void test3(int* p) {
*p = 3;
}
void test4(int* p) {
test(p);
cout << *p << endl; // 3
}
void test5(int** p) {
**p = 5;
}
void test6(int* p) {
test5(&p);
cout << *p << endl; // 5
}
int main() {
//int* iNum = NULL;
//test(iNum);
cout << *iNum;
//test2(&iNum);
//cout << *iNum;
//int i = 2;
//test3(&i);
//cout << i << endl;
//system("pause");
int i = 3;
test4(&i);
cout << i << endl; // 3
test6(&i);
cout << i << endl; // 5
system("pause");
return 0;
}
测试代码2:
#include <iostream>
using namespace std;
void test(int *p) {
*p = 999;
cout << p << " " << &p << " " << *p << endl; // 0x61fe8c 0x61fe70 999
}
void pointer(int *p) {
int a = 11;
cout << p << " " << &p << " " << *p << endl; // 0x61febc 0x61fea0 22
// 理解:传参是复制了一个同样指向 b 的指针
*p = 555;
cout << *p << endl; // 555
p = &a;
cout << &a << " " << p << " " << &p << " " << *p << endl;
// 0x61fe8c 0x61fe8c 0x61fea0 11
*p = 33;
test(p);
cout << *p << " " << a << endl; // 999 999
}
int main() {
int b =22;
int *p = &b;
cout << &b << endl; // 0x61febc
cout << p << " " << &p << " " << *p << endl; // 0x61febc 0x61feb8 22
pointer(p);
cout << p << " " << &p << " " << *p << endl; // 0x61febc 0x61feb8 11
cout << b << endl; // 555
}