strcat concat a char onto a string?
strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.
Since you don't know what that memory even refers to, you should expect problems when your code accesses it.
In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.
Because ¤tChar
is not a string, it doesn't finish with \0
character. You should define B
as char *currentChar = 'B';
. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string
should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.
Or if you want to use char
then you can do something like (depending of your code):
char string[256];
...
char currentChar = 'B';
size_t cur_len = strlen(string);
if(cur_len < 254) {
string[cur_len] = currentChar;
string[cur_len+1] = '\0';
}
else
printf("Not enough space");
I think the simplest method (not efficient) would be sprintf
sprintf(str, "%s%c", str, chr);
As responded by others, ¤tChar is a pointer to char or char*, but a string in C is char[] or const char*.
One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.
Example:
Making a simple string, with only 1 character and the suffix '\0';
char cToStr[2];
cToStr[1] = '\0';
Applying to your question:
char * string = "";
char currentChar = 'B';
cToStr will assume the string "B":
cToStr[0] = currentChar;
And strcat will work!
strcat ( string, cToStr );