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 开发者_Python百科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 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;
}
If you wish to join a single character, you will have to write a separate function that takes the quantity of characters from s2
to append.
The best is to create a new function that allows adding a single char to a string.
But if you would like to use the join()
function as it is for some reason, you can also proceed as follows:
char *command = "nest";
char *buffer = " "; // one space and an implicit trailing '\0'
char *halloween;
*buffer = command[0];
halloween = join("hallowee", buffer);
精彩评论