+ 1
Why there is no output in the following code? (Code below) Please help! 🥺
#include <stdio.h> #include <string.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; } No output. Why? Please explain! 🙏🙏🥺
2 ответов
+ 4
1. the `strlen` function does not exist. You need to include the <string.h> header file
2. In C, every string ends with a '\0' (null) character. So if the length of a string is 5, its 5th index would be '\0'. Also, the %s specifier in the printf function only prints a string till it encounters '\0'
In your code, the `length` variable stores the value 6 (length of "string" is 6)
Now let's see what will happen in the first iteration of the for loop, when i = 0
p[i] = s[length - i]
=> p[0] = s[6 - 0]
=> p[0] = s[6]
As I said above, the 6th index of a string of length 6 is always a null character. Therefore the 0th index of p is assigned a null character which prevents it from being printed. The fix is simple - simply change `s[length - i ]` to `s[length - i - 1]` so that the null character at the end is ignored
3. Again, in C, every string must end with a null character. But the char array p is not terminated by null. You will need to add a line
p[length] = '\0';
+ 2
XXX Thanks a lot! 🙏🙏😊😊 Extremely helpful! ☺️☺️