1.1k views

Consider the following C program segment:

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

The output of the program is

1. gnirts
2. string
3. gnirt
4. no output is printed
is it "length-I" or "length -i".please clarify!!
its corrected. its length-i

Here,

$p[0] = s[length] =$ '\0'; //compiler puts a '\0' at the end of all string literals

Now, for any string function in C, it checks till the first '\0' to identify the end of string. So, since the first char is '\0', printf %s, will print empty string. If we use printf("%s", p+1); we will get option (C) with some possible garbage until some memory location happens to contain "\0". For the given code, answer is (D).

edited by
@arjun sir : i got the answer . but you have written if we write print("%s,p+1) ; will get option c

This is possible only if after t we have null else it will print from p[1] to p[19] ryt ?
Yes, you are correct. But it doesn't stop at p[19] - it keeps on printing until some memory location has value 0 ('\0').
yes i had this on my mind . Yeah :D
no output
edited