指针作为参数传递

函数参数传递的只能是数值,所以当指针作为函数参数传递时,传递的是指针的值,而不是地址。

相关阅读: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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值