将指针传递给一个函数,然后将其放入另一个函数中

Taking a pointer passed to a function, then putting it into another function

本文关键字:函数 然后 另一个 指针 一个      更新时间:2023-10-16

我正在编写一个可以读写文件的密码生成器。我有一个函数,它接受一个空字符串,然后修改它

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]);
}
相关文章: