将char*传递给函数c++

Passing char* to a function c++

本文关键字:函数 c++ char      更新时间:2023-10-16

所以我有这个问题无法解决:-(在我的.h中,我有这个:

protected:
   char* _textPath_1;
   FileReader* _reader_3;

在.cpp中我有:

_reader_3 = new FileReader();
_textPath_1 = "foo";
_reader_3->openFile(_textPath_1);

FileReader有这个:

private:
   char* fileName;
public:
   signed int openFile(char* name);

但是如果我写这个(只是为了测试):

signed int FileReader::openFile(char* name) {
    std::cout << name << std::endl;
    fileName = name;
    stream.open(fileName, std::ios::in);
    if (!stream.is_open()) {
        FileReader::printErrorOpeningFile(fileName);
        stream.close();
        return -1;
    }
   return 0;
}

fileName是一个char*,我需要它获得相同的name值(foo)。我收到一个错误,我甚至无法打印姓名,它只打印了一行空白。。为什么?

编辑:即使使用strcpy也不起作用。。实际上,在函数内部,我无法打印name的值,这就像它被"去初始化"了

您需要为文本字符串_textPath_1分配空间。试试这个。

char myTextString[] = "foo";
_textPath_1 = myTextString;

这将创建一个本地字符数组(字符串),该数组被初始化为"foo"。然后,它将该字符串的地址复制到您的字符指针_textPath_1。作为LOCAL存储,它只在本地代码块中有效,一旦您的代码退出其范围,它将不可用。如果您需要该字符串通过本地代码块,则需要从堆内存中分配它(例如使用new),并记住在处理完它之后取消分配它

不能将strcpy与未分配的指针一起使用,因为strcpy希望目标char*指向充当目标字符串缓冲区的字符数组。由于您根本没有分配任何字符空间,它无法将"foo"复制到您的_textPath_1中,这就是为什么当您尝试strcpy时会出现运行时错误。

char*的这些和其他乐趣就是std::string被发明的原因。不用担心分配和释放空间,必须使用strcpy来复制其值等等。考虑使用std::string _textPath_1来代替char* _textPath_1

在调用函数之前,必须分配_reader_3。

FileReader*_reader_3=新的FileReader;

我假设fileName是您的成员变量。访问指针而不进行初始化将导致不可预测的结果

如果您真的在头文件中定义全局变量:

char* _textPath_1;
FileReader* _reader_3;

那你不应该那样做。全局变量应在头文件中声明,但应在实现文件中定义。


此代码运行良好:

#include <iostream>
#include <fstream>
struct FileReader {
    char* fileName;
    std::fstream stream;
    signed int FileReader::openFile(char* name) {
        std::cout << name << std::endl;
        fileName = name;
        stream.open(fileName, std::ios::in);
        if (!stream.is_open()) {
            FileReader::printErrorOpeningFile(fileName);
            stream.close();
            return -1;
        }
        return 0;
    }
    void printErrorOpeningFile(char *) {}
};
int main() {
    char* _textPath_1;
    FileReader* _reader_3;
    _reader_3 = new FileReader();
    _textPath_1 = "foo";
    _reader_3->openFile(_textPath_1);
    delete _reader_3;
}