Append Char To String in C?
Solution 1:
char* str = "blablabla";
You should not modify this string at all. It resides in implementation defined read only region. Modifying it causes Undefined Behavior.
You need a char array not a string literal.
Good Read:
What is the difference between char a[] = "string"; and char *p = "string";
Solution 2:
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);
/* one for extra char, one for trailing zero */
char *str2 = malloc(len + 1 + 1);
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.