+ 2

Please help me to find the error in my code because the output should be "amalhello" because of concat

https://code.sololearn.com/c5nTCkuL037A/?ref=app

27th Jan 2020, 9:31 PM
Amal Gil
Amal Gil - avatar
5 Réponses
+ 1
You need to allow enough "room" in str1 to accommodate str2. When you declare char pointers and try to strcat them.... the compiler will not complain...but when you run the it...it will not work and the prog will fail. But when you declare the char pointer with a const....the compiler with stop compiling if you attempt the change it. Your last question....just use char arrays for you user input e.g. char str1[20]; fgets(str1, 20, stdin);
27th Jan 2020, 11:13 PM
rodwynnejones
rodwynnejones - avatar
+ 1
#include <stdio.h> #include<string.h> int main() { char str1[20]="amal"; char str2[]="hello"; printf("str1 is :%s , str2 is :%s\n",str1, str2); int longeur1=0,longeur2=0; longeur1=strlen(str1); longeur2=strlen(str2); printf("str1 est:%s et sa longeur :%d\n",str1, longeur1); printf("str2 ets :%s et sa longeur :%d\n",str2, longeur2); strcat(str1, str2); printf("the whole string is %s",str1); return 0; } http://www.cplusplus.com/reference/cstring/strcat/
27th Jan 2020, 10:08 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Thank you so much It is working now
27th Jan 2020, 10:19 PM
Amal Gil
Amal Gil - avatar
+ 1
Okay so you meant that when we are using pointers the string can not changed Please my question is :how can we use pointer in this case and the string is entered by the user??
27th Jan 2020, 10:46 PM
Amal Gil
Amal Gil - avatar
0
Just to add;- You can still use - char *str2="hello"; and it should really be defined as "const char *str2="hello";"
27th Jan 2020, 10:40 PM
rodwynnejones
rodwynnejones - avatar