250 views
8 8 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int a[] = {5, 10, 15};
    int *p = a;

    printf("%d ", (*p)++);
    printf("%d ", *p++);
    printf("%d ", ++*p);
    printf("%d", *++p);

    return 0;
}
  1. $\texttt{5 6 11 15}$
     
  2. $\texttt{5 10 11 15}$
     
  3. $\texttt{6 6 11 15}$
     
  4. $\texttt{5 6 10 15}$

1 Answer

1 1 vote

 

Initial array:

$\texttt{a[0] = 5}$

$\texttt{a[1] = 10}$

$\texttt{a[2] = 15}$

Initially, $\texttt{p}$ points to $\texttt{a[0]}$.

First print:

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

This prints the current value of $\texttt{a[0]}$, then increments $\texttt{a[0]}$.

So, it prints $\texttt{5}$.

Now $\texttt{a[0]}$ becomes $\texttt{6}$.

Second print:

$\texttt{*p++}$

This means $\texttt{*(p++)}$.

So, it first prints the value at current $\texttt{p}$, then moves $\texttt{p}$ to the next element.

Currently, $\texttt{p}$ is still pointing to $\texttt{a[0]}$.

So, it prints $\texttt{6}$.

Then $\texttt{p}$ moves to $\texttt{a[1]}$.

Third print:

$\texttt{++*p}$

This means increment the value pointed to by $\texttt{p}$.

Now $\texttt{p}$ points to $\texttt{a[1]}$.

So, $\texttt{a[1]}$ changes from $\texttt{10}$ to $\texttt{11}$.

Then it prints $\texttt{11}$.

Fourth print:

$\texttt{*++p}$

This means first move $\texttt{p}$ to the next element, then dereference it.

So, $\texttt{p}$ moves from $\texttt{a[1]}$ to $\texttt{a[2]}$.

Then it prints $\texttt{a[2]}$, which is $\texttt{15}$.
 

$\therefore$ Output : $\texttt{5 6 11 15}$
 

Answer : A

• edited by
Answer:
Position:
Show:

Related questions

9 9 votes
2 2 answers
404
404 views
GO Classes asked Jun 20
404 views
What is the output of the following code?#include <stdio.h int main() { int a[] = {10, 20, 30, 40}; int *p = a; int *q = &a[3]; if (p < q) p = p + 2; else q = q - 1; prin...
9 9 votes
2 2 answers
389
389 views
GO Classes asked Jun 20
389 views
What is the output of the following code?#include <stdio.h int main() { int a [3] = { {1, 2, 3}, {4, 5, 6} }; int (*p)[3] = a; printf("%d %d %d", p, *(*(p + 1) + 2), *(*...
10 10 votes
1 1 answer
243
243 views
GO Classes asked Jun 20
243 views
What is the output of the following code?#include <stdio.h void change(int pp, int *q) { pp = pp + 3; *pp = q; pp = pp + 4; } int main() { int a = 5, b = 10; int *p ...
8 8 votes
1 1 answer
245
245 views
GO Classes asked Jun 20
245 views
What is the output of the following code?#include <stdio.h int main() { int a = 10; int *p = &a; int q = &p; q = q + 5; *p = *p + 2; printf("%d %d", a, q); return 0; ...