将指针传递给一个函数,然后将其放入另一个函数中
Taking a pointer passed to a function, then putting it into another function
我正在编写一个可以读写文件的密码生成器。我有一个函数,它接受一个空字符串,然后修改它
void password_create(string *passwd)
在这个函数中,我调用了一个写函数,它用密码写入一个文件,看起来像这样:
void write_out(string file_name, string *passwd)
然后总代码看起来像这样:
void password_create(string *passwd) {
*passwd = "something";
write_out(&passwd);
}
编译程序抱怨我无法将std::basic_string<char>**
转换为std::basic_string<char>*
。
我对C++还比较陌生,这个程序只是为了帮助我熟悉这种语言。我可以将passwd
传递到write_out()
函数中,而不需要*
或&
来表示指针或引用。如果我键入,它不会给我错误
*passwd = "something";
write_out(passwd);
这并不影响整个程序的完成,我只是好奇为什么会出现这个错误。
变量passwd
已经是指向std::string
的指针,因此通过&passwd
获取它的地址会得到std::string**
类型的东西-因此,如果write_out
期望std::string*
类型的参数,但收到std::string**
,则编译器会给您一个错误,如您所见。所以在将passwd
传递给write_out()
:时不要使用&
write_out(passwd);
但除此之外,您应该通过引用而不是通过指针传递std::string
变量,如注释和其他答案中所述。
不要使用指针,在c++中更喜欢使用pass-by-reference:
void password_create(std::string &passwd) {
passwrd = "something";
...
然后确保按照您的意愿创建字符串:
std::string myString;
password_create(myString);
这样,您将拥有所需的内存,并且不需要担心指针语义。
无需将事情过于复杂。我看不出在这种情况下哪里需要指针。只需制作一个函数来生成密码并返回即可。
#include <string>
#include <fstream>
using namespace std;
string password_create() {
return "generated password";
}
void write_password_to_file(string file, string password) {
ofstream stream(file);
stream << password;
stream.close();
}
int main() {
auto password = password_create();
write_password_to_file("pathtofile.txt", password);
return 0;
}
正如其他答案中所提到的,您实际上应该通过引用而不是指针来获取std::string
参数。
假设write_out()
有一些类似的签名
write_out(char* passwd);
或
write_out(const char* passwd);
你可以通过std::string::operator[]()
:
void password_create(string *passwd) {
*passwd = "something";
write_out(&(*passwd)[0]);
}
- 为什么我的递归函数按降序打印,然后按升序打印?
- 等待整个 omp 块完成,然后再调用第二个函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么 ComPtr 的函数返回不同的值,然后 &?
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 如何在C++中获取lua函数作为参数,然后调用它
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- 使用函数打开文件,然后让其他函数利用该文件?
- C++:将向量传递给函数,然后在main中调用函数.错过了什么
- 努力将指向成员函数的指针绑定到类模板的T成员,然后在槽中调用
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- C++大括号初始值设定项作为参数调用不同的构造函数,然后预期
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 如何在 LLVM 传递期间破坏然后解散函数?
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃
- 需要在调用函数然后检查errno之前清理errno
- 声明一个没有内容的函数;-然后是内容{}- c++