The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+20 votes

Consider the following C program segment:

char p[20]; int i;
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
asked in Programming by Veteran (52k points)
edited by | 2.1k views
is it "length-I" or "length -i".please clarify!!
its corrected. its length-i

2 Answers

+29 votes
Best answer


$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).

answered by Veteran (407k points)
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

Please let me know why the answer for printf("%s", p+1) is option c) and not option a). I'm confused because when i=5, (ie., i<6 holds) we get to print the character 's' too, right?


length is string= 6  it stores as string% end with endmarker%

for loop will make it = %gtrin [s is left out since we can store 6 letters, (a) is answer when sizeof is used intead of length]

Now print(p+1) = grint  [ see here end marker is not present so after reaching index 20 it will halt.

Thank you :)
error as i not declarēd
You got an eagles eye no one noticed that.

@Anu007..means in Sizeof you count null character also.....i have one doubt also.....array of string starting from 0   why not 1...or is it by default....please help me

+5 votes
no output
answered by Active (1.9k points)
edited by
Strlen(s)  gives 6 as null is not counted then how can null be the first char in p and hence no output.

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,530 questions
54,139 answers
71,068 users