+ 6

C Challenge Question

Why it gives no output, #include <stdio.h> #include <string.h> int main() { char str[10]; char *s = "string"; int length = strlen(*s); for(int i=0; i<length; i++) str[i] = s[length - i]; printf ("%s",str); return 0; }

23rd Jul 2020, 12:21 PM
Ashwini Adsule
Ashwini Adsule - avatar
2 Respostas
+ 4
It is because you're copying '\0' into str[0]. That means strlen(str) will be 0. In other words, str is empty and there's nothing to print. int length = strlen(*s); // should be without the * also. Below is an updated version that reverses the string as you likely want: #include <stdio.h> #include <string.h> int main() { char str[10]; char *s = "string"; int length = strlen(s); str[length] = '\0'; // mark end of string. for(int i=0; i<length; i++) str[i] = s[length - i - 1]; printf ("%s",str); return 0; }
23rd Jul 2020, 12:34 PM
Josh Greig
Josh Greig - avatar
+ 2
Thank you.
23rd Jul 2020, 12:42 PM
Ashwini Adsule
Ashwini Adsule - avatar