将char*传递给函数c++
Passing char* to a function c++
所以我有这个问题无法解决:-(在我的.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;
}
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗