Don't use gets
to read the data from the user, If you enter the input more then the array size arr2[10]
, The array holds the 10 bytes, So there is no space for \0
. It leads to "Undefined Behavior"
Due to this you are getting-
qwertyuiop
qwert
qwertyuiopqwert // Note the extra characters with arr2, That is more then your input
Use fgets
to read input from user-
fgets(arr2,10,stdin);
Then the program is working fine. Try this change-
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[13] = "abcdefg";
char arr2[10];
// gets(arr2);
fgets(arr2,10,stdin); // it will read only 9 characters from user, 1 byte for null
puts(arr2);
strncat(arr1, arr2, 5);
puts(arr1);
puts(arr2);
return 0;
}
Output-
root@sathish1:~/My Docs/Programs# ./a.out
qwertyuiopasdf <- i have entered more than 10 character. But it reads only first 9 byte
qwertyuio
abcdefgqwert
qwertyuio