Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change the value of a string.

Status
Not open for further replies.

jbsys

Programmer
May 6, 2005
51
0
0
CA
Hi;
I'm having trouble understanding how to change the value of a string parameter being passed into a DLL function. Here's what i have in the function.


void TestGetEnvVar(char *parm1)
{
char enval[]="The dll has changed the value.";
*parm1 = char(&enval);
return;
}


my call is:
parm1 = "original value";

TestGetEnvVar(parm1);

What I expect parm1 to contain when it comes back to the calling program is "The dll has changed then value."

What is acually coming back is: "Toriginal value"
Can someone enlighten me as to what is actually going on here? I am also for a method by which I can change the value of the string being passed into the function.

Thanks
jbsys.

 
If yourfunction prototype is
Code:
void f(char*);
don't pass string literals to it!
Code:
f("Don't pass me to modify!!!"); // Wrong call.
String literals in C/C++ in fact are constant values. You can't modify them. Alas, for backward compatibilty they don't have const attribute.
In this case you pass a pointer to char array in f(). Now f() may use it to modify:
Code:
void f(char* p)
{
...
   p[0] = '\?';
   p[1] = 0;
/* or */
   strcpy(p,"I want to overrun this char array! Bye...");
... // and so on
}
It's a very (very) unsafe op, never use it. Pass a pointer and a buffer size (the 2nd arg) to prevent buffer overrun, or better use std::string and pass it safely:
Code:
void f(std::string& s)
{
...
   s = "Now std::string allocate a memory for me. Thanks.";
...
}
 
>What is acually coming back is: "Toriginal value"

Really?

I'd expect "Triginal value"

Code:
void TestGetEnvVar(char *parm1)
param1 is a pointer to a char. As such can be treated as an array of chars - but pointer to char is all the compiler "knows".

Code:
*parm1
Dereferences the pointer - ie gives access to the char parm1 points to.

Thus
Code:
*parm1 = char(&enval);
Assigns the first char in the parm1 array the value of the first char in enval.

I agree with ArkM - use the std::string.
Another simple prototype that'd be less confusing to use could be

Code:
std::string TestGetEnvVar()
{
  return "The dll has changed the value.";
}

...
{
  std::string s = "Original value";
  ...
  s = TestGetEnvVar();
}



/Per
[sub]
www.perfnurt.se[/sub]
 
Since the function is in a DLL, I don't think passing a std::string is safe. You'd need to pass (const char* buffer, int size)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top