edited by
12,807 views
34 votes
34 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
edited by

2 Answers

Best answer
48 votes
48 votes

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
7 votes
7 votes
no output
edited by
Answer:

Related questions

28 votes
28 votes
3 answers
1
Kathleen asked Sep 18, 2014
14,252 views
Consider the following C function:int f(int n) { static int i = 1; if(n >= 5) return n; n = n+i; i++; return f(n); }The value returned by $f(1)$ is:$5$$6$$7$$8$
24 votes
24 votes
2 answers
2
Kathleen asked Sep 18, 2014
8,898 views
The goal of structured programming is to:have well indented programsbe able to infer the flow of control from the compiled codebe able to infer the flow of control from t...
26 votes
26 votes
5 answers
4
Kathleen asked Sep 18, 2014
6,904 views
Choose the best matching between the programming styles in Group 1 and their characteristics in Group 2.$$\begin{array}{|ll|ll|}\hline \rlap{\textbf{Group 1}} & & \rlap{...