How do I append a single char to a string in C?
i.e
char* str = \"blablabla\";
char c = \'H\';
str_append(str,c); /* blablablaH */
C does not have strings per se -- what you have is a char pointer pointing to some read-only memory containing the characters "blablabla\0". In order to append a character there, you need a) writable memory and b) enough space for the string in its new form. The string literal "blablabla\0" has neither.
The solutions are:
1) Use malloc()
et al. to dynamically allocate memory. (Don't forget to free()
afterwards.)
2) Use a char array.
When working with strings, consider using strn*
variants of the str*
functions -- they will help you stay within memory bounds.