edited by
13,505 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
50 votes
50 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

15.1k
views
3 answers
29 votes
Kathleen asked Sep 18, 2014
15,124 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$
9.3k
views
2 answers
24 votes
Kathleen asked Sep 18, 2014
9,268 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 the program textavoid the use of GOTO statements
15.2k
views
5 answers
30 votes
Kathleen asked Sep 18, 2014
15,246 views
Consider the following functionvoid swap(int a, int b) { int temp; temp = a; a = b; b = temp; }In order to exchange the values of two variables $x$ and ... return any value$swap (x, y)$ cannot be used as the parameters are passed by value
7.2k
views
5 answers
26 votes
Kathleen asked Sep 18, 2014
7,245 views
Choose the best matching between the programming styles in Group 1 and their characteristics in Group 2. ... 4 \quad R-1\quad S-2$P-3\quad Q-4\quad R-2\quad S-1$