My Visual Studio C++ seems to be passing the wrong values when it comes to function arguments.

Paul Arnold 1 Reputation point
2022-11-30T21:10:13.527+00:00

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?

Developer technologies | Visual Studio | Debugging
Developer technologies | C++
{count} votes

2 answers

Sort by: Most helpful
  1. David Lowndes 4,726 Reputation points
    2022-11-30T21:14:47.56+00:00

    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;  
    }  
    
    0 comments No comments

  2. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2022-12-01T02:14:20.34+00:00

    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.