To append a char to a string in C, you first have to ensure that the memory buffer containing the string is large enough to accomodate an extra character. In your example program, you'd have to allocate a new, additional, memory block because the given literal string cannot be modified.
Here's a sample:
#include <stdlib.h>
int main()
{
char *str = "blablabla";
char c = 'H';
size_t len = strlen(str);
char *str2 = malloc(len + 1 + 1 ); /* one for extra char, one for trailing zero */
strcpy(str2, str);
str2[len] = c;
str2[len + 1] = '\0';
printf( "%s\n", str2 ); /* prints "blablablaH" */
free( str2 );
}
First, use malloc
to allocate a new chunk of memory which is large enough to accomodate all characters of the input string, the extra char to append - and the final zero. Then call strcpy
to copy the input string into the new buffer. Finally, change the last two bytes in the new buffer to tack on the character to add as well as the trailing zero.