0

I'm working on a software using a home-made report library which takes only (const char *) type as an argument :

ReportInfo(const char* information);
ReportError(const char* error);
[...]

As I'm trying to report value of integers, I'd like to get a representation of those integers in a const char* type. I can do it that way :

int value = 42;
string temp_value = to_string(value);
const char *final_value= temp_value.c_str();
ReportInfo(final_value);

It would be great if I could do it without instancing the temp_value. I tried this :

int value = 42;
const char* final_value = to_string(value).c_str();
ReportInfo(final_value);

but final_value is equal to '\0' in that case.

Any idea how to do it ?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
augustin-r
  • 13
  • 6

2 Answers2

6

You could try

ReportInfo(to_string(value).c_str());

because the temporary will not be destroyed until ReportInfo returns.

alain
  • 11,939
  • 2
  • 31
  • 51
4

to_string(value) returns a temporary, so in your second example its lifetime ends at the end of the expression. so you have dangling pointer.

Jarod42
  • 203,559
  • 14
  • 181
  • 302