Search code examples
cjoincharstrcatconst-char

How can I join a char to a constant char*?


I have a function that joins two constant char* and returns the result. What I want to do though is join a char to a constant char* eg

char *command = "nest";
char *halloween =  join("hallowee", command[0]);   //this gives an error

char *join(const char* s1,  const char* s2)
{
    char* result = malloc(strlen(s1) + strlen(s2) + 1);

    if (result)
    {
            strcpy(result, s1);
            strcat(result, s2);
    }

    return result;
}

Solution

  • The function you wrote requires two C-strings (i.e. two const char * variables). Here, your second argument is command[0] which is not a pointer (const char *) but a simple 'n' character (const char). The function, however, believes that the value you passed is a pointer and tries to look for the string in memory adress given by the ASCII value of the letter 'n', which causes the trouble.

    EDIT: To make it work, you would have to change the join function:

    char *join(const char* s1,  const char c)
    {
        int len = strlen(s1);
        char* result = malloc(len + 2);
    
        if (result)
        {
                strcpy(result, s1);
                result[len] = c;         //add the extra character
                result[len+1] = '\0';    //terminate the string
        }
    
        return result;
    }