C语言指针作为函数参数 以及智能指针作为函数参数

本文详细介绍了指针在C++中作为函数参数的四种传递方法:普通指针、指针引用、字符串指针赋值及智能指针共享。通过示例代码展示了各种方法下指针值的变化,帮助读者理解指针传递的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总所周知指针作为函数参数传递的时候 传递的是指针的拷贝(指针也是变量) 这里提供四种指针的传递方法 改到实际的指针。

#include <stdio.h>
#include <memory>
#include <iostream>
using namespace std;
void test1(char **string)
{
	printf("string未操作之前的的指针%p\n",string);
	*string = "hello world";
	printf("string未操作之后的的指针%p\n",string);
}
char *test(char *string)
{
	string = "hello world";
	return string;
}
void test2(char *&string)
{
	string = "hello world";
	
}

bool test3(shared_ptr<int> &ptr)
{
    if(ptr)
        return true;
    ptr=make_shared<int>(10);

    return false;
}
int main3()
{
	shared_ptr<int>p;
    cout<<test3(p);
    cout<<test3(p)<<endl;
    cout<<*p;

	getchar();
	return 0;
}

int main()
{
	char *str = NULL;
	test2(str);
	printf("str=%s\n",str);

	getchar();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值