Concatenating string

I have an expression:

const char* client_name = "client"+ std::to_string(getpid())

But I get error like below:

client.cpp:54:20: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]

How do I solve this ?
The error doesn't make sense to me, given that code. But even if it compiled, that code would be incorrect. If std::string had an implicit conversion to const char *, since you're assigned from a temporary the const char * pointer would be immediately invalid.

1
2
auto client_name_string = "client" + std::to_string(getpid());
const char *client_name = client_name_string.c_str();
client_name_string must be kept alive until you no longer need client_name.
Last edited on
std::to_string() gives you an std::string object, not a char* pointer!

Try something like this:
1
2
std::string client_name = std::string("client") + std::to_string(getpid());
const char *ptr = client_name.c_str(); /* <-- this pointer is valid as long as the std::string object 'client_name' exists! */


...or, alternatively:
1
2
char buffer[32];
snprintf(buffer, 32, "client %d", getpid());
Last edited on
Thanks both method are working.

I have similar blocks of code in the same program. When I try:
char in_buffer [256];
This perfectly compiles and works. But when I do following, it fails:
1
2
const std::string str0;
const char* in_buffer = str0.c_str()


How can I make the second method work ?
Last edited on
Well if you add the terminating ; to L2 it compiles OK.

But what are you trying to achieve?
Last edited on
std::string::c_str() gives you the pointer to the internal buffer of the std::string object. This pointer will be valid only as long the std::string object still exists and if no modifications are made to the string object.

Hence, getting the pointer to an empty (default-constructed) string object isn't really helpful.

You could just as well write:
const char* in_buffer = ""; // ...instead of: empty_string.c_str();

If, later, you plan to append something to the std::string object, it is likely that the internal buffer will be re-allocated and therefore the pointer that you received earlier is invalidated! So, this would be a bad idea:
1
2
3
4
std::string str0;
const char* buffer = str0.c_str();
str0 += "hello world!";
do_something_with(buffer); // <-- pointer 'buffer' is probably invalid at this point! 


But why do you even need a "raw" pointer? Can't you pass, e.g., a const reference to std::string object?

1
2
3
4
5
6
7
8
9
10
void do_something_with(const std::string &string_ref)
{
    /* ... */
}

int main()
{
    std::string client_name = std::string("client") + std::to_string(getpid());
    do_something_with(client_name);
}
Last edited on
Topic archived. No new replies allowed.