0

I can't concatenate two pointer strings using strcat, is it not possible?

I tried using them like strcat(s1,s2), and strcat(*s1,*s2), and all and it still doesn't work.

char *s1="Hello";
char *s2="Bye";
printf("%s\n",s1);
strcat(s1,s2);
printf("%s",s1);

When I run it prints the first "Hello" that is before the strcat, but the code doesn't display the remaining output and doesn't return 0.

  • `s1` and `s2` are string literals which resides in const memory location. Instead string literals you should have array of chars to concatenate two strings. – Sunil Bojanapally Mar 28 '19 at 09:50

1 Answers1

4

Your approach cannot work, for several reasons:

char *s1="Hello";

s1 points to a read-only string (literal). You cannnot modify it.

strcat(s1,s2);

This cannot work because there is not enough room in s1 to add s2.

Use:

char s1[30]="Hello";
char *s2="Bye";

strcat(s1,s2);

With char s1[30]="Hello"; the compiler allocates an array for 30 charactes and then copies the string "Hello" into that array. Unused elements are set to zero.

With char *s2="Bye"; the compiler makes s2 point to a read-only string, so to make that explicit it is better to write const char *s2="Bye";

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41