关于函数参数中有指针无法带出地址

本文介绍了一个C++函数,用于读取整个文件到内存中,并探讨了解决函数接口问题的方法。通过修改参数传递方式从值传递改为引用传递解决了sfile始终为null的问题。

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

本人菜鸟一只,写了一个读入全部文件的函数,接口一直有问题,代码如下:

int ReadAllFile(wstring sfilepath, WCHAR*sfile,int mod)
{
	wifstream file(sfilepath.c_str(), std::wifstream::binary);
	
	WCHAR*szencr;
	
	if (file)
	{
		// Calculate the file's size, and allocate a buffer of that size.
		file.seekg(0, file.end);
		const int file_size = file.tellg();

		if (file_size > (1024 * 10000))
		{
			file.close();
			//delete szencr;
			return -1;
		}


		// Read the entire file into the buffer.
		file.seekg(0, file.beg);
		szencr = new WCHAR[file_size + 1];
		memset(szencr, 0, file_size + 1);
		//szencr = file.rdbuf();
		file.read(szencr, file_size);
		//file.getline(szencr, file_size);
		file.close();
		sfile = szencr;//希望传出地址
		return 0;

	}
	else
	{
		return -1;

	}
	
}

但是这样出来的sfile 一直为null,一直以为sfile 就是个地址,我传的地址进去,就应该能带出地址,实际上是不行的,应该将参数改成如下:

int CSkfControl::ReadAllFile(wstring sfilepath, WCHAR*&sfile,int mod)//引用传递,不是引用的话,值传递,一直不知道指针也是可以引用传递的。。。。。太菜了
{
	wifstream file(sfilepath.c_str(), std::wifstream::binary);
	
	WCHAR*szencr;
	
	if (file)
	{
		// Calculate the file's size, and allocate a buffer of that size.
		file.seekg(0, file.end);
		const int file_size = file.tellg();

		if (file_size > (1024 * 10000))
		{
			file.close();
			//delete szencr;
			return -1;
		}


		// Read the entire file into the buffer.
		file.seekg(0, file.beg);
		szencr = new WCHAR[file_size + 1];
		memset(szencr, 0, file_size + 1);
		//szencr = file.rdbuf();
		file.read(szencr, file_size);
		//file.getline(szencr, file_size);
		file.close();
		sfile = szencr;
		return 0;

	}
	else
	{
		return -1;

	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值