Search code examples
ccharconcatenationprepend

how to concatenate a char to a char* in C?


How can I prepend char c to char* myChar? I have c has a value of "A", and myChar has a value of "LL". How can I prepend c to myChar to make "ALL"?


Solution

  • This should work:

    #include <string.h>    
    char * prepend(const char * str, char c)
    {
        char * new_string = malloc(strlen(str)+2);  // add 2 to make room for the character we will prepend and the null termination character at the end
        if (new_string) {
            new_string[0] = c;
            strcpy(new_string + 1, str);
        }
        return new_string;
    }
    

    Just remember to free() the resulting new string when you are done using it, or else you will have a memory leak.

    Also, if you are going to be doing this hundreds or thousands of times to the same string, then there are other ways you can do it that will be much more efficient.