adding space in strcat

Mazzy picture Mazzy · Aug 8, 2013 · Viewed 23.9k times · Source

I have two strings char str1[41] e char str2[41]. If I use strcat function to concatenate them I get an unique string without space instead I would have space between these.

this could be a way:

strcat(strcat(str1, " "),str2)

Does it exist another way?

Answer

mah picture mah · Aug 8, 2013

sprintf(destination, "%s %s", str1, str2);

You'll have to provide a destination. You could use str1 as your destination and it might work correctly, but note the way you're currently doing things could cause you to overrun str1s buffer.

asprintf() will allocate a buffer for you, of the correct (read: safe) length, but you must remember to free() that buffer when you're done with it.