D
darren
Hi everybody, have a quick look at this code:
=====
=====
int main(void) {
string msg;
makeString(msg);
cout << "back in main, result = " << msg << endl;
return EXIT_SUCCESS;
}
void makeString(string& message){
char theMessage[25] = "Here is a char array";
message = theMessage;
cout << "insdie the makeString func,theMesage = '" << message <<
endl;
}
=====
=====
I would like to write functions that return strings that i can simply
assign to a string (or char*) from my calling function. The above
code achieves the result i want, but it looks a bit strange to me (I
have a java background). I would prefer the makeString function to
return the string, instead of adjusting a reference to a string that
is passed to it. I would rather it not take a variable at all.
The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense. I could make a string on the
heap and return a pointer to it, but then do i have manage freeing up
space for that string when i'm done using it in the calling mfunction?
this seems like a lot of extra work.
thank you for any advice.
=====
=====
int main(void) {
string msg;
makeString(msg);
cout << "back in main, result = " << msg << endl;
return EXIT_SUCCESS;
}
void makeString(string& message){
char theMessage[25] = "Here is a char array";
message = theMessage;
cout << "insdie the makeString func,theMesage = '" << message <<
endl;
}
=====
=====
I would like to write functions that return strings that i can simply
assign to a string (or char*) from my calling function. The above
code achieves the result i want, but it looks a bit strange to me (I
have a java background). I would prefer the makeString function to
return the string, instead of adjusting a reference to a string that
is passed to it. I would rather it not take a variable at all.
The problem i have found is that making the string in the makeString()
function, then returning it does not work because the stackframe for
that function is destroyed when the function ends, so referencing a
tring variable in there makes no sense. I could make a string on the
heap and return a pointer to it, but then do i have manage freeing up
space for that string when i'm done using it in the calling mfunction?
this seems like a lot of extra work.
thank you for any advice.