0

I'm new to c++ , I'm working on a project that uses std::string and then converts that string to char* to be used in functions that are going to be exported.

However, I'm getting an empty string when I debug it.

#include <iostream>
#include <string>

void fun(char* &x, char* &y)
{
    std::string tmp = "hello"; 
    std::string temp = "world";
    x = &tmp[0];
    y = &temp[0];

}
int main()
{
    char* x;
    char* y;

    fun(x, y);
}

enter image description here enter image description here

Best regards.

deadc0der7
  • 301
  • 5
  • 17
  • `tmp` and `temp` go out of scope and are destroyed when `fun` ends. The pointers are no longer valid. – 001 Sep 01 '21 at 12:15
  • you should use [`std::string::c_str`](https://en.cppreference.com/w/cpp/string/basic_string/c_str) to get a pointer to the strings buffer, though that pointer is also only valid as long the string is alive – 463035818_is_not_an_ai Sep 01 '21 at 12:16
  • can you give me an example for that situation – deadc0der7 Sep 01 '21 at 12:34

0 Answers0