You're making a classic error - returning a pointer to something that no longer exists.
Have your function return a string:
string meth()
{
string sret = "Hello";
return sret;
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Visual Studio 2022
When I do:
const char* meth(){
string sret = "Hello";
return sret.c_str();
}
cout << meth() << endl;
what I get back is not sret.
I think that I have a problem passing arguments too.
How do I fix this?
You're making a classic error - returning a pointer to something that no longer exists.
Have your function return a string:
string meth()
{
string sret = "Hello";
return sret;
}
Hi @Paul Arnold ,
The value declared inside the function is saved on the stack, and the space on the stack will be released automatically after the execution of the function is completed.
Using your code in the main function will get "Hello".
int main() {
string str1="Hello world";
cout << str1.c_str() << endl;
}
If you still want to output variables of const char* through function, you could try the following code.
const char* meth() {
const char* sret = "Hello";
return sret;
}
Best regards,
Elya
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.