+ 7
Why there is no output in this code?
#include <stdio.h> int main() { char p[20]; char *s="string"; int length=strlen(s); for (int i=0; i<length;i++){ p[i]=s[length-i]; printf("%s",p); } return 0; }
1 Answer
+ 6
The C-string "string" length is equal to `strlen("string") + 1` because the null terminator ('\0') is also part of a C-string (strlen() won't count the '\0') which is a signal for end-of-string and as you proceed to the loop body, the null terminator is the first character that is going to be stored in p[0] unless the expression `s[length - i]` become `s[length - i - 1]`, a null terminator gets added to the "one past the last element of the p array", and finally the whole reversed string gets printed.
int main()
{
int i;
char p[20];
char *s = "string";
int length = strlen(s);
for (i = 0; i < length; i++) {
p[i] = s[length - i - 1];
}
p[i] = '\0';
printf("%s\n", p);
}
Output: gnirts