strcat paste second string at beginning of first string

Refael picture Refael · May 26, 2013 · Viewed 27.3k times · Source

i use strcat() to connect two strings like:

    #include <string.h>
    #include <stdio.h>

    int main(int argc, char *args[])
    {
       char *str1; // "456"
       char *str2; // "123"

       strcat(str1,str2);
       printf("%s",str1);
    }

i get:

456123  

but i need the second string on beginning of first string like:

123456

how can i do it ?

Answer

Rohan picture Rohan · May 26, 2013

Do strcat(str2,str1);, switch the parameters. But you will get resultant string in str2, which you can set to str1 if you really want to use str1 further in your program.

However, you need to take care appropriately for memory space available in str2.


If you want to change str1 then, do this

char *tmp = strdup(str1);

strcpy(str1, str2); //Put str2 or anyother string that you want at the begining
strcat(str1, tmp);  //concatenate previous str1

...
free(tmp); //free the memory