0

So, How can i assign std::string through a function?

i have this code

void WP_Hash(std::string dest, std::string src) { // Set up all the locals struct NESSIEstruct whirlpool_ctx; char digest[64], buffer[4100]; unsigned char *tmp = (unsigned char *)digest; // Start the hashing NESSIEinit(&whirlpool_ctx); NESSIEadd((const unsigned char *)src.c_str(), src.length() * 8, &whirlpool_ctx); // Finish the hashing NESSIEfinalize(&whirlpool_ctx, tmp); // Convert to a real string unsigned int len = 0; while (len< 128) { buffer[len++] = gch[*tmp >> 4]; buffer[len++] = gch[*tmp & 0x0F]; tmp++; } buffer[128] = 0; dest.assign(buffer); } 

and this code to initialize it:

 std::string ret; WP_Hash(ret, "none"); sampgdk::logprintf("%s", ret.c_str()); 

It print nothing

when i change ret string to "a", it print "a" i want it print none (hashed in WP_Hash but ignore about it, let's say that "none" is the result of WP_Hash)

what could i do?

2 Answers 2

3

C++ is not Java: its objects have value semantics. So, you're passing a copy into that function.

Pass a reference instead if you want the original argument to keep the changes from within the function. (It is also worth passing a (const) reference to src to save copying it unnecessarily.)

 void WP_Hash(std::string& dest, const std::string& src); // ^ ^^^^^^ ^ 

Alternatively, return the result string from the function instead:

 std::string WP_Hash(const std::string& src); // ^^^^^^^^^^^ ^^^^^^ ^ 

then use as such:

const std::string ret = WP_Hash("none"); sampgdk::logprintf("%s", ret.c_str()); 
Sign up to request clarification or add additional context in comments.

Comments

0

Same as any other C++ type - pass by value unless specified otherwise. Add a & to make it a reference. Or just return it.

4 Comments

can you giveme example where i can put & ?, i have try to put it WP_Hash(&ret, "none"); but it show error Cannot convert argument 1 from 'std::string *' to 'std::string'
@RaefaldhiAmartya: Programming by guessing will not work. You should put some effort into actually learning the language.
@LightnessRacesinOrbit ok thanks for the suggestion. i dont have a c++ book, i just read c++ tutorial in tutorialspoint, i dont find what i search about.
@RaefaldhiAmartya: Get a C++ book. You cannot learn the language from random tutorials on the internet. In fact, you're more likely to learn it wrong!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.