Originally Posted by
Sebastiani
>> strcat does not work
the second argument to strcat is a character array, try:
strcat(s, "s");
or, just traverse the string yourself, append the char where the NULL was, increment, then add a NULL (just be sure the string has enough space allocated to it to accomadate the new data).
NULL is a macro that should only be used in pointer context. The myriad meanings of null can potentially confuse people, so you should be more specific. In this case, "null character" would be more appropriate than any lexical variation of "null". NULL is the worst possible choice in my opinion because it means something completely different than what you were using it for.
>>How do I add a character to a C string (char array)?
Provided the array has enough room, strcat can be used as shown previously. Though if the character you wish to add is a variable, strcat will not work unless it too is a string. In the case where there is enough room and the character to be added is not a string, you will need to find the end of the array and perform the modification manually. Here is one way to go about it:
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char str[12] = "Programmer";
char ch = 's';
size_t end;
end = strlen(str);
str[end] = ch;
str[end + 1] = '\0';
puts(str);
return 0;
}
Notice that the expression end + 1 is used. If there is not enough room in the array, this would assign to memory outside of the array boundaries, resulting in undefined behavior. So you should be very careful when working directly with strings like this. To avoid the potential problems, you can write a function to do it for you. Then you have a fully tested and debugged routine to call:
Code:
#include <stdio.h>
#include <string.h>
void append(char *str, char ch);
int main()
{
char str[12] = "Programmer";
char ch = 's';
append(str, ch);
puts(str);
return 0;
}
void append(char *str, char ch)
{
size_t end = strlen(str);
str[end] = ch;
str[end + 1] = '\0';
}