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 */
The Original poster didn't mean to write:
char* str = "blablabla";
but
char str[128] = "blablabla";
Now, adding a single character would seem more efficient than adding a whole string with strcat. Going the strcat way, you could:
char tmpstr[2];
tmpstr[0] = c;
tmpstr[1] = 0;
strcat (str, tmpstr);
but you can also easily write your own function (as several have done before me):
void strcat_c (char *str, char c)
{
for (;*str;str++); // note the terminating semicolon here.
*str++ = c;
*str++ = 0;
}
Easiest way to append two strings:
char * append(char * string1, char * string2)
{
char * result = NULL;
asprintf(&result, "%s%s", string1, string2);
return result;
}
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";