I want to add "$" to the end of the string, I've seen that I can use strcat() and I wrote the following code:
char *word = "1000";
const char *dollar = "$";
strcat(word,dollar);
printf("%s", word);
It compiles, but when I run the little program I get Segmentation fault (core dumped).
Where is the error?
I know that strcat is:
char *strcat(char *dest, const char *src);
The problem is that you are trying to concatenate to a literal string. Literal strings are constant and can not be changed.
You need to create the "destination" as an array instead, containing enough characters to fit your concatenation:
char word[16] = "1000";
The number 16 in the array above I picked arbitrary. It has to be at least big enough to fit the string you put in it, plus the length of the string you concatenate, plus the terminating '\0' character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With