Raefaldhi Amartya
Raefaldhi Amartya

Reputation: 73

How assign std::string through a function?

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?

Upvotes: 0

Views: 88

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

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());

Upvotes: 3

MSalters
MSalters

Reputation: 179907

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

Upvotes: 0

Related Questions