• edited by
36,464 views
87 87 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$

5 Answers

Best answer
177 177 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
1 1 vote

char c[] ="GATE2011";

char *p = c;

printf("%s", p + p[3] - p[1]);

Concept - Pointer arithmetic 

p[3] = *(p+3) = E

p[1] = *(p+1) = A 

ASCII VALUE DIFFERENCE OF E-A = 4

so finally printf("%s", p +4]); here p is the pointing to the address  first element of char array c[ ] and p +4 will point to Address of P[4] element of array , printf takes initial address and prints untill "\0" is found, so final output will be  2011

Answer:
Position:
Show:

Related questions

75 75 votes
4 answers 4 answers
24.3k
24.3k views
go_editor asked Sep 29, 2014
24,344 views
On a non-pipelined sequential processor, a program segment, which is the part of the interrupt service routine, is given to transfer $500$ bytes from an I/O device to mem...
78 78 votes
9 answers 9 answers
29.5k
29.5k views
go_editor asked Feb 14, 2015
29,467 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...
175 175 votes
9 answers 9 answers
47.7k
47.7k views
Misbah Ghaya asked Feb 13, 2015
47,680 views
What is the output of the following C code? Assume that the address of $x$ is $2000$ (in decimal) and an integer requires four bytes of memory.int main () { unsigned int ...