C++ 使用char数组指针通过引用调用
我需要从函数中读取二进制文件中的流。我想通过引用char*来调用它,以便在最后有一个指向流的开始的指针。然而,我的每一次尝试都没有改变指针,或者导致内存访问冲突 我从另一个函数调用该方法 下面是调用函数:C++ 使用char数组指针通过引用调用,c++,pointers,reference,call,C++,Pointers,Reference,Call,我需要从函数中读取二进制文件中的流。我想通过引用char*来调用它,以便在最后有一个指向流的开始的指针。然而,我的每一次尝试都没有改变指针,或者导致内存访问冲突 我从另一个函数调用该方法 下面是调用函数: APP_ERROR EncryptionHandler::encryptFile(char *file) { char *i_Stream = ""; // I get a compiler error if I dont initialize this if(this->readFil
APP_ERROR EncryptionHandler::encryptFile(char *file)
{
char *i_Stream = ""; // I get a compiler error if I dont initialize this
if(this->readFileStream("picture.png", i_Stream) != OPERATION_SUCCESSFUL) // Call the function and return a custom error, if the function does so
return ERROR_FILE_READING;
}
这里是读取文件的函数
APP_ERROR EncryptionHandler::readFileStream(char *fileName, char *Stream)
{
char *fileStream;
FILE *file = fopen(fileName, "rb");
// Some logic to get the file size
fileStream = new char[maxFileSize];
fread(fileStream, 1, maxFileSize, file); // Fill the stream with the fread function
fclose(file);
Stream = fileStream; // Set the given Pointer to my fileStream pointer
return OPERATION_SUCCESSFUL;
}
然而,在调用函数中,变量i_流从未改变。稍后,它仍然指向“”导致我的程序出现问题
我不明白这一点,因为我设置了给定指针=我的fileStream指针
但是,以下方法不起作用:
this->readFileStream("picture.png", char &i_Stream);
i_Error EncryptionHandler::readFileStream(char *fileName, char **Stream)
this->readFileStream("picture.png", char *i_Stream);
i_Error EncryptionHandler::readFileStream(char *fileName, char &Stream)
我认为像memcpy这样的过程是不对的,因为我已经得到了指向流的指针。他们还造成了访问冲突错误
必须有一种简单的方法将文件读取函数中的流指针指定给调用方法变量
我不能使用函数的返回值,因为我使用的是我自己的错误系统,如您所见
它也是二进制数据,不欢迎使用任何字符串
那么,通过引用调用char数组的正确方法是什么呢?您应该将
EncryptionHandler::readFileStream()
声明为
APP_ERROR EncryptionHandler::readFileStream(char *fileName, char *&Stream)
注意参数流的类型
。通过指针的引用,您可以将Stream
内部readFileStream()
的更改传递回调用者
在没有引用的情况下,指针被简单地复制到
readFileStream()
除了@timrau所说的之外,我还看到了内存分配问题。我没有看到任何代码分配内存来保存从文件中读取的数据。类似下面的代码应该可以工作
PP_ERROR EncryptionHandler::readFileStream(char *fileName, char*& Stream)
{
char *fileStream;
FILE *file = fopen(fileName, "rb");
// Some logic to get the file size
// Allocate memory for the data.
fileStream = new char[maxFileSize];
fread(fileStream, 1, maxFileSize, file); // Fill the stream with the fread function
fclose(file);
Stream = fileStream; // Set the given Pointer to my fileStream pointer
return OPERATION_SUCCESSFUL;
}
只需使用Stream
,就可以稍微简化函数
PP_ERROR EncryptionHandler::readFileStream(char *fileName, char*& Stream)
{
FILE *file = fopen(fileName, "rb");
// Some logic to get the file size
// Allocate memory for the data.
Stream = new char[maxFileSize];
fread(Stream, 1, maxFileSize, file); // Fill the stream with the fread function
fclose(file);
return OPERATION_SUCCESSFUL;
}
哦,非常感谢你,你救了我一晚!理解这一点。这是指向引用的指针吗?或对指针的引用?*&我觉得有点困惑是的,当然。我在文件读取方法中有
fileStream=new char[maxFileSize]
来分配内存;)谢谢你的提示