edited by
20,129 views
42 votes
42 votes

What does the following fragment of C program print?

    char c[] = "GATE2011";
    char *p = c;
    printf("%s", p + p[3] - p[1]);
  1. $\text{GATE2011}$
  2. $\text{E2011}$
  3. $2011$
  4. $011$
edited by

2 Answers

Best answer
102 votes
102 votes

2011 is the answer. 

In C, there is a rule that whatever character code be used by the compiler, codes of all alphabets and digits must be in order. So, if character code of '$A$' is $x$, then for '$B$' it must be $x+1$. 

Now $\%s$ means printf takes and address and prints all bytes starting from that address as characters till any byte becomes the code for $'\0'.$ Now, the passed value to printf here is
$p + p[3] - p[1]$

$p$ is the starting address of array $c. p[3] = 'E'$ and $p[1] = 'A'$. So, $p[3] - p[1] = 4$, and $p + 4$ will be pointing to the fifth position in the array c. So, printf starts printing from $2$ and prints $2011$. 

(Here $``\text{GATE2011}”$ is a string literal and by default a $'\0'$ is added at the end of it by the compiler). 

NB: In this question $\%s$ is not required. 

 printf(p + p[3] - p[1]);

Also gives the same result as first argument to printf is a character pointer and only if we want to pass more arguments we need to use a format string. 

edited by
Answer:

Related questions

47 votes
47 votes
8 answers
2
go_editor asked Feb 14, 2015
15,858 views
Consider the following C program segment.# include <stdio.h int main() { char s1[7] = "1234", *p; p = s1 + 2; *p = '0'; printf("%s", s1); }What will be printed by the pro...