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;
}
The function you wrote requires two C-strings (i.e. two
const char *variables). Here, your second argument iscommand[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
joinfunction: