-3

I want to write a program that gets the first half of a string 'ch1' and puts it in a string 'ch3' then gets the first half of another string 'ch2' and concatenates it in 'ch3' "puts is in the end of ch3" but when I execute it, it gives me weird output for ch3 .. for example :

ch1 ="123"
ch2 ="azertyuiop"

the result : ch3 ="1<3rdweirdletter>azert"

This is my code :

int main()
{ 
char ch1[200],ch2[200],ch3[200]; 

puts("give 'ch1' ");
gets(ch1);
puts("give 'ch2' ");
gets(ch2);

strncpy(ch3,ch1, strlen(ch1)/2 );
strncat(ch3,ch2, strlen(ch2)/2 );

printf("a half \"%s\" + a half \"%s\" gives \"%s\"",ch1,ch2,ch3);

return 0;
}

I would appreciate if someone helps me. Thanks

ivpavici
  • 1,117
  • 2
  • 19
  • 30

1 Answers1

2

You can either initialize ch3[] to be all zeroes: char ch3[200] = { 0 }; Or you can manually place the null-terminator (the character '\0') on ch3 after copying the first half of ch1 to it:

strncpy(ch3, ch1, strlen(ch1) / 2);
ch3[strlen(ch1)/2] = '\0';
strncat(ch3, ch2, strlen(ch2) / 2);

This is needed because strings in C need to be null-terminated (meaning you need a value of 0 after the last character of the string to mark the end of the string). The function strncpy(s, ct, n) only pads with zeroes if ct has less characters than n (not your case), therefore, if you don't add the null character manually, strncat will think that ch3 is much longer. It will search for the first zero in memory after ch3's start and only there it will concatenate what you wanted. That's where those weird characters come from.

sthiago
  • 453
  • 1
  • 6
  • 14