GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 33

Copying the terminator before reversed characters

Programming in C · Arrays & Strings · Full GATE CSE 2004 paper

GATE 2004, Q33 2 marks · MCQ
Report issue

Arrays & Strings

Question 33, GATE 2004: What is printed by this C fragment? Assume appropriate declarations/includes for i, strlen and printf.
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 %s format follows GFG. GateForum visibly prints a malformed alternate format rather than %s.
Options:
(A) gnirts
(B) string
(C) gnirt
(D) No output is printed
Tap to enlarge
Your answer
Answer & solution

Answer: D under the displayed intended C fragment (no official key was published)

1. The source length is 6. At i=0, p[0]=s[length−0]=s[6], which is the string terminator.

2. Consequently printf with %s sees an empty string immediately, regardless of later copied characters, and prints nothing, D. This uses the paper’s %s format and assumes surrounding declarations/includes for i and the library functions.

4. Teaching check: The source string positions are 0:s,1:t,2:r,3:i,4:n,5:g,6:\0. The very first assignment copies position 6 into p[0].

Original paper, page 4