+ 2
Why this code isn't accepted as a solution for Extra-Terrestrials? It works perfect in Code Playground.
#include <stdio.h> #include <string.h> int main() { char a[]= "garbage"; int i; for(i=strlen(a);i>=0;i--) { printf("%c",a[i]); } return 0; }
6 odpowiedzi
+ 3
A string is an array of characters. Like with arrays of any other type, the last element is located not at position
size
but at
size - 1
since arrays are zero-indexed. Keep this in mind when initializing the loop variable.
+ 1
Hi Shadow, I played with the loop a little bit and these are some outputs on Code Playground:
... strlen(a); egabrag \\ output
strlen(a)-1; egabrag \\ I'm not sure if I propperly understood your answer, but this one you probably suggested.
strlen(a)+1; egabrag
strlen(a)-2; gabra
strlen(a)+2; egabrag
strlen(a)+10; @?egabrag
Could someone please explain me why this code(any of the mentioned except strlen(a)-2;)) isn't accepted as a solution for extra-terrestrials with more details?
+ 1
It depends on how they evaluate your solution. I am not an expert when it comes to this stuff, but this is how I would see it.
You might have heard that C-strings are null-terminated:
https://en.m.wikipedia.org/wiki/Null-terminated_string
That means that for a string s, the condition
s[ strlen( s ) ] == '\0'
holds true.
However, the null-termination character has no visual represantation, so upon printing it, you won't actually notice it, although it is still send to the output buffer.
So my guess is that SoloLearn gets what you wrote to the output buffer, and compares that to their solution. When initializing the running variable to
strlen( s )
you print the null-termination character too, so it is also 'part of your solution', although not visually. Due to that extra character, the comparison fails and your solution is evaluated to be wrong.
Here is an example of this process:
https://code.sololearn.com/cnrekTMmuKLO/?ref=app
Try playing around with the 'i' in the first loop and see what happens.
+ 1
Danke Shadow, your Buffer Example really helped me. Although neither my last solution was accepted. Could you please look at it? Again it works in Code Playground...
+ 1
You are the best! Thanx again..
0
It is not accepted because you still start printing at the null-termination character, not the actual last character in the string, which is what I've been trying to explain earlier. You should start printing at position
strlen( s ) - 1
in the string.