225 views
6 6 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    char str[] = "GATE";
    char *p = str;

    printf("%c %c %s", str[1], *(p + 2), p + 1);

    return 0;
}
  1. $\texttt{G A GATE}$
     
  2. $\texttt{A T ATE}$
     
  3. $\texttt{A T TE}$
     
  4. $\texttt{T A ATE}$

2 Answers

0 0 votes


The string is:

$\texttt{str = "GATE"}$

So, the characters are:

$\texttt{str[0] = 'G'}$

$\texttt{str[1] = 'A'}$

$\texttt{str[2] = 'T'}$

$\texttt{str[3] = 'E'}$

Now,

$\texttt{p = str}$

So, $\texttt{p}$ points to the first character of the string.

First expression:

$\texttt{str[1]}$

This gives $\texttt{'A'}$.

Second expression:

$\texttt{*(p + 2)}$

Since $\texttt{p}$ points to $\texttt{str[0]}$, $\texttt{p + 2}$ points to $\texttt{str[2]}$.

So,

$\texttt{*(p + 2) = 'T'}$

Third expression:

$\texttt{p + 1}$

This points to $\texttt{str[1]}$.

When printed using $\texttt{\%s}$, it prints the string from that position.

So, it prints:

$\texttt{"ATE"}$
 

$\therefore$ Output : $\texttt{A T ATE}$


Answer: B

edited by
Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
250
250 views
GO Classes asked Jun 23
250 views
What is the output of the following code?#include <stdio.h int main() { char str[] = "CODE"; char *p = str; p++; *p = 'A'; printf("%s %c", str, *(p + 2)); return 0; }$\te...
6 6 votes
1 1 answer
201
201 views
GO Classes asked Jun 23
201 views
What will happen when the following code is compiled?#include <stdio.h int main() { int a[] = {10, 20, 30}; a = a + 1; printf("%d", *a); return 0; }$\texttt{10}$ $\texttt...
5 5 votes
1 1 answer
194
194 views
GO Classes asked Jun 23
194 views
Consider the following declarations:#include <stdio.h int main() { int a[4] = {6, 4, 1, 2}; int b[8] = {9, 8, 11, 10, 5, 7, 0, 3}; int *p = &a ; int *q = b; printf("%p", ...
7 7 votes
2 2 answers
256
256 views
GO Classes asked Jun 23
256 views
What is the output of the following code?#include <stdio.h int main() { int a[] = {5, 10, 15, 20}; int *p = a + 1; printf("%d %d %td", *(p + 1), p , (p + 2) - a); return ...