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; }
6 Respostas
+ 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.
+ 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.
+ 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';
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
0
Gen2oo I tired i=1 also .. which is s[length-1] or s[5] ...s[5] is g ..but still prints nothing
0
Gen2oo but if I give char s[] instead of char *s it is working fine it is printing