Eckhard Lehmann wrote:
> schrieb:
> > What is the right way of creating a string/char array and assigning to
> > a char* which is then used in a function call. Thought it would be
>
> First of all, remember: char* is a _pointer_ to a char.
> Not a string, not an array or anything else goofy. Just a pointer.
>
> > quite nice to avoid a memory leakage /core dump.
>
> If you want to use char*, memory management is up to you. However, if
> you use functions that return char*, you may rely on the fact, that the
> memory is properly allocated there.
>
> >
> > 1 Header with char* x
> >
> > 2 Class includes header
> >
> > 3 In Class member function I want to :
> > a)conditionally create a string ie populate x
> > b)pass (populated) x on as a function parameter.
> >
> > What is the right way of doing this for :
> > i) assigning string variable
> > ii) assigning a literal.
> >
> > i) Since it's a conditional create I guess it is not a good idea to use
> > malloc or new.
> >
> > ii) Is it ok to just have x = "some string";
> >
>
> What is the problem here? Hard to figure out what you mean, can you post
> any code?
>
>
> Eckhard
Ok here is some code but in other places I would deal with char* /
char[] and not a string.
void f2(string &s)
{
s="qwerty";
}
void f1(myStruct &ms)
{
string s;
f2(s);
// Error 203: # Cannot assign 'char *' with 'const char *'.
//ms.cp = s.c_str();
ms.cp = (char*)s.c_str();
}
int main () {
myStruct mystruct;
f1(mystruct);
cout << mystruct.cp << endl;
return 0;
}
Note:
1) am stuck with using a char* - non-negotiable.
2) That I get Error 203 and need to cast seems to indicate this isn't
the correct way.
3) I did wonder if the s.c_str() would go out of scope leaving f1()
i.e. is this dangerous?
4) I would have thought it would be best to allocate memory to the
char* in main() but at that point the string size is unknown.
Sorry for the delay in responding.