216 views
10 10 votes

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 = &a;

    change(&p, &b);

    printf("%d %d %d", a, b, *p);

    return 0;
}
  1. $\texttt{8 10 8}$
     
  2. $\texttt{8 14 14}$
     
  3. $\texttt{5 14 14}$
     
  4. $\texttt{8 14 8}$

1 Answer

0 0 votes


 

In $\texttt{main()}$:

$\texttt{a = 5}$, $\texttt{b = 10}$

and

$\texttt{p}$ points to $\texttt{a}$.

Now the function call is:

$\texttt{change(\&p, \&b)}$

So, inside the function:

$\texttt{pp}$ points to $\texttt{p}$.

$\texttt{q}$ points to $\texttt{b}$.

First statement:

$\texttt{**pp = **pp + 3}$

Since $\texttt{*pp}$ is $\texttt{p}$, and $\texttt{p}$ points to $\texttt{a}$, this changes $\texttt{a}$.

So,

$\texttt{a = 5 + 3 = 8}$

Second statement:

$\texttt{*pp = q}$

This changes $\texttt{p}$ itself.

Now $\texttt{p}$ no longer points to $\texttt{a}$.

Now $\texttt{p}$ points to $\texttt{b}$.

Third statement:

$\texttt{**pp = **pp + 4}$

Now $\texttt{p}$ points to $\texttt{b}$, so this changes $\texttt{b}$.

So,

$\texttt{b = 10 + 4 = 14}$

At the end:

$\texttt{a = 8}$

$\texttt{b = 14}$

$\texttt{p}$ points to $\texttt{b}$, so $\texttt{*p = 14}$.
 

$\therefore$ Output : $\texttt{8 14 14}$
 

Answer: B

• edited by
Answer:
Position:
Show:

Related questions

9 9 votes
2 2 answers
296
296 views
GO Classes asked Jun 20
296 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), *(*...
8 8 votes
1 1 answer
214
214 views
GO Classes asked Jun 20
214 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; ...
9 9 votes
2 2 answers
323
323 views
GO Classes asked Jun 20
323 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...
8 8 votes
1 1 answer
223
223 views
GO Classes asked Jun 20
223 views
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)...