Do you think this is the best approach?
Definitely not. The memory of buf is going out of scope when enclosing block } ends. The lifetime of buf ended. After that, the name pointer points to invalid memory location. Dereferencing the pointer, for example by printing the content of memory the pointer points to, is invalid.
This is my first method using a char array:
And it's almost perfect. A seasoned programmer might prefer snprintf to protect against buffer overflow:
char name[30];
snprintf(name, sizeof(name), "Name: %s", "Ricardo");
But you are using C++ - no need to use C interfaces. If you want to dynamically allocate memory, use stringstream and such, for example:
std::stringstream ss;
// stringstream resizes internal buffer to accommodate input
// ie. "the string will contain only the memory needed"
ss << "Name: " << "Ricardo";
// std::string automatically frees memory in destructor
std::string name = ss.str();
or really, if you do not need formatting capabilities of stringstream, then just std::string:
std::string name = std::string() + "Name: " + "Ricardo";
If you want to dynamically allocate memory using C interfaces, you typically call snprintf twice, as shown to the answer in sprintf() with automatic memory allocation? . If you are using newlib as standard library, asprintf() might also be available.