why does this code crash?
is using strcat
illegal on character pointers?
#include <stdio.h>
#include <string.h>
int main()
{
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
printf("%s",s3);
return 0;
}
please give a proper way with referring to both array and pointers.
The problem is that s1
points to a string literal and you are trying to modify it by appending s2
to it. You are not allowed to modify string literals. You need to create a character array and copy both strings into it, like so:
char *s1 = "Hello, ";
char *s2 = "world!";
char s3[100] = ""; /* note that it must be large enough! */
strcat(s3, s1);
strcat(s3, s2);
printf("%s", s3);
"Large enough" means at least strlen(s1) + strlen(s2) + 1
. The + 1
is to account for the null terminator.
That having been said, you should seriously consider using strncat
(or the arguably better but nonstandard strlcat
, if it is available), which are bounds-checked, and thus are far superior to strcat
.
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