大佬教程收集整理的这篇文章主要介绍了将“char *”指针传递给函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我设置了一个类来读取文件。 将 char * 类型的指针传递给函数,该函数将文件写入指针指向的内存单元。 最后,期待通过函数外的指针读取文件内容。 但结果并没有达到预期。 在程序内部,有一个结果输出。 但在外面,没有结果。我不知道为什么。
#include <fstream>
#include <stdlib.h>
namespace my
{
class file
{
file() = default;
~file() = default;
bool ReadTo(char * _out,const char * _path);
}
}
bool my::file::readTo(char * _out,const char * _path)
{
std::ifstream fs;
//infs lengfsh;
fs.open(_path);
fs.seekg(0,std::ios::end);
long len = fs.tellg();
//goes well at this,output normally
printf("my::file::readTo >> len:%d\n",len);
fs.seekg(0,std::ios::beg);
_out = (char *)malloc(sizeof(char) * len);
fs.read(_out,len);
//goes well at this,output normally
printf("my::file::readTo >> out:%s\n",_out);
fs.close();
return true;
}
int main()
{
char * txt;
my::file mf;
mf.ReadTo(txt,"x:\\xxxx\\demo.txt");
// result shows : NulL
deBUG("demo.txt >> \n %s\n",txt);
}
参数 char * _out
将是传递的内容的副本,因此修改它不会影响传递的内容。
您应该将 &
添加到它(声明和定义),如 char * &_out
以使其成为引用,以便对其的修改将反映到调用者中指定为参数的内容。>
还要确保读取的是 C 样式字符串(以空字符结尾的字符序列)。换句话说,不要使用不包含任何值为 0x00 的字节的文件来测试您的程序。否则,printf()
的读数将超出范围,可能会发生危险的事情。
以上是大佬教程为你收集整理的将“char *”指针传递给函数全部内容,希望文章能够帮你解决将“char *”指针传递给函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。