0

why it prints nothing?? please clarify me this doubt

#include <stdio.h> #include<string.h> int main() { char p[20]; char *s = "string"; int length = strlen(s); int i; for (i = 0; i < length; i++) {      p[i] = s[length - i]; printf("%s",p); } return 0; }

10th Jul 2020, 7:11 PM
C Lover
6 Réponses
+ 1
If you begin at i = 1, it leaves p[0] uninitialized and won't copy the entire string. p[0] may contain 0 or some other garbage value (if it is zero, the result is the same as a null-termination). So you must subtract 1 from the length. You then add the null-terminator when you're done copying.
10th Jul 2020, 8:13 PM
Gen2oo
Gen2oo - avatar
+ 1
Because it copies the null-byte at the end of the string to the beginning, so printf() believes you passed it an empty string. Make it p[i] = s[length - i - 1]; and put the printf() statement outside the for-loop.
10th Jul 2020, 7:32 PM
Gen2oo
Gen2oo - avatar
+ 1
C Lover Array indexing begins at 0 and s[5] is the last character in the string, but strlen(s) returns 6. s[6] contains the null-terminating byte. So you must subtract one from the length. The string is terminated at the first iteration: p[0] = s[6 - 0] where s[6] = '\0';
10th Jul 2020, 7:46 PM
Gen2oo
Gen2oo - avatar
0
why it prints nothing?? please clarify me this doubt Gen2oo #include <stdio.h> #include<string.h> int main() { char p[20]; char *s = "string"; int length = strlen(s); int i; for (i = 1; i < length; i++) {      p[i] = s[length - i]; printf("%s",p); } return 0; } I gave i=1 so s[length-] must not be null right but still prints nothing
10th Jul 2020, 7:33 PM
C Lover
0
Gen2oo I tired i=1 also .. which is s[length-1] or s[5] ...s[5] is g ..but still prints nothing
10th Jul 2020, 7:48 PM
C Lover
0
Gen2oo but if I give char s[] instead of char *s it is working fine it is printing
10th Jul 2020, 8:14 PM
C Lover