+ 1

Why is strcat() not working in my code properly?

I want the nouv() function to copy the first half of each string and concatenate them in a new string which will be returned by the function. //this is the source code #include <stdio.h> #include <stdlib.h> #include <string.h> char nouv(char ch1[128], char ch2[128]) { char ch3[128]; int l1,l2,i,j; l1= strlen(ch1); l2= strlen(ch2);   for(i=0;i<l1/2;i++){     ch3=strcat(ch3,ch1[i]);   }  for(i=0;i<l2/2;i++){     ch3=strcat(ch3,ch2[i]);   }   printf("Aprés la concaténation = %s\n", ch3);   return ch3; } char nouv(char ch1[128], ch2[128]); int main(){ char str1[128], str2[128]; printf("Donner chaine1:\n"); scanf("%s",str1); printf("Donner chaine2:\n"); scanf("%s",str2); nouv(str1,str2); return 0; }

28th Mar 2022, 11:00 PM
Syrine Ayedi
Syrine Ayedi - avatar
3 Answers
+ 5
I think strcat is the wrong function for this task. Instead, use strncat, which limits the number characters that it copies. Also, both functions do the looping for you. ch3 is uninitialized, so it starts with a garbage string. The mismatched return value is a pointer to a local variable whose memory gets released upon function exit. That can corrupt the returned string. But the return value is not even used, so you might as well make the function void instead. Here are my corrections to make it work: void nouv(char ch1[128], char ch2[128]) { char ch3[128] = ""; int l1,l2; l1= strlen(ch1); l2= strlen(ch2); //for(i=0;i<l1/2;i++){ strncat(ch3,ch1,l1/2); //} //for(i=0;i<l2/2;i++){ strncat(ch3,ch2,l2/2); //} printf("Aprés la concaténation = %s\n", ch3); return; } //char nouv(char ch1[128], ch2[128]); ^^^^^ This function prototype is unnecessary because the function itself is already defined before main() where it gets used.
28th Mar 2022, 11:28 PM
Brian
Brian - avatar
+ 3
Brian thank you so much appreciate your help 😊
29th Mar 2022, 12:18 AM
Syrine Ayedi
Syrine Ayedi - avatar
0
Nice code Syrine Ayedi Isn't Brian really helpful! May I also add, scanf() will stop at the first space, might even cause overflow so the second variable takes the characters after the first space. Perhaps you are getting a user to enter their name or a sentence, maybe you could consider fgets(str1, 127, stdin);
29th Mar 2022, 1:46 AM
HungryTradie
HungryTradie - avatar