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\n",str[0]);
I even tried the below code which fails as well
char *str1 = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s\n",str1);
Can someone explain this?
TIA.
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.
A way to do it is this
Instead of 100 you can choose a size such that concatenation (including the final NULL character) to have place to happen.
This code illustrates the problem:
Output
To concatenate two strings you either have to create a new one large enough tp contain the both source strings or the one of the strings shall be large enough to hold the second appended string.
Take into account that string literals are immutable in C (and C++). Any attempt to change a string literal results in undefined behaviour.
You could concatenate strings if one of them was stored in a character array.
For example
Or you could create a third string.