What will be the output of the following code fragment?

What will be the output of the following code fragment?

char p[20];
char *s = "string";
int length = strlen(s);
for(i = 0; i < length; i++)
{
        p[i] = s[length - i];
}
printf("%s",p);

a) string        b) gnirts        c) nirts        d) No output

Answer

The result will be: d) No output
It seems that the code fragment reverses the given string "string". But actually what happened is that, at the first iteration of the loop, the following statement is executed p[0] = s[length - 0]. As we know that at s[length] the null character '\0' is stored, i.e. it will become the first character in the new string p. Since, character array p contains first character as '\0', when the compiler is executing the code it will treat it as end of the string. Hence, no output.
 

0Comment