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
s1points to a string literal and you are trying to modify it by appendings2to it. You are not allowed to modify string literals. You need to create a character array and copy both strings into it, like so:“Large enough” means at least
strlen(s1) + strlen(s2) + 1. The+ 1is to account for the null terminator.That having been said, you should seriously consider using
strncat(or the arguably better but nonstandardstrlcat, if it is available), which are bounds-checked, and thus are far superior tostrcat.