Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to concatenate 2 character arrays but when I try it does not work and my o/p console hangs and does not print anything.

   char *str[2];
   str[0] = "Hello ";
   str[1] = "World";
   strcat(str[0],str[1]);
   printf("%s
",str[0]);

I even tried the below code which fails as well

   char *str1 = "Hello ";
   char *str2 = "World";
   strcat(str1,str2);
   printf("%s
",str1);

Can someone explain this?

TIA.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

char *str1 = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s
",str1);

Here you have str1 point to a static zone of memory which may be on a read-only page and strcat tries to write in this area at the end of "Hello " string.

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable.

A way to do it is this

char str1[100] = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s
",str1);

Instead of 100 you can choose a size such that concatenation (including the final NULL character) to have place to happen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...