Append Char To String in C?

前端 未结 9 1106
滥情空心
滥情空心 2020-11-27 16:17

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 */
9条回答
  •  一生所求
    2020-11-27 16:33

    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.

提交回复
热议问题