Here I want to merge two char arrays and put them into the first char array But when I cout the second one, it is missing the first letter. why?
#include <bits/stdc++.h>
using namespace std;
int main() {
char s1[4] = "one";
char s2[4] = "two" ;
strcat(s1, s2);
cout << s1 << endl; //onetwo
cout << s2; // wo
return 0;
}
When calling the function
strcat, it is required that you pass as the first argument a pointer to a memory buffer that is large enough to store the concatenated string.In your case, the concatented string has a length of 6 characters (
"onetwo"), so the memory buffer must have a size of at least 7 characters (including the terminating null character). However, in your case, the memory buffer has a size of only 4 characters, which is insufficient. Therefore, your program is invoking undefined behavior, which means that anything can happen. This includes the behavior that you describe in the question.To fix the problem, you must make the array
s1at least 7 characters long:This program has the desired output: