300 views
7 7 votes

What is the output of the following code?

#include <stdio.h>

void update(int **q, int *r) {
    **q = **q + 5;
    *q = r;
    **q = **q + 2;
}

int main() {
    int x = 3, y = 8;
    int *p = &x;

    update(&p, &y);

    printf("%d %d %d", x, y, *p);

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

3 Answers

1 1 vote


In $\texttt{main()}$:

$\texttt{x = 3}$

$\texttt{y = 8}$

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

Function call:

$\texttt{update(\&p, \&y)}$

So, inside $\texttt{update()}$:

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

$\texttt{r}$ points to $\texttt{y}$.

First statement:

$\texttt{**q = **q + 5}$

Since $\texttt{q}$ points to $\texttt{p}$ and $\texttt{p}$ points to $\texttt{x}$,

$\texttt{**q}$ refers to $\texttt{x}$.

So,

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

Second statement:

$\texttt{*q = r}$

Here, $\texttt{*q}$ means $\texttt{p}$.

So, this changes $\texttt{p}$ itself.

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

Third statement:

$\texttt{**q = **q + 2}$

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

So, $\texttt{**q}$ refers to $\texttt{y}$.

Therefore,

$\texttt{y = 8 + 2 = 10}$

At the end:

$\texttt{x = 8}$

$\texttt{y = 10}$

$\texttt{p}$ points to $\texttt{y}$, so $\texttt{*p = 10}$
 

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


Answer: B

Answer:
Position:
Show:

Related questions

8 8 votes
3 3 answers
333
333 views
GO Classes asked Jun 25
333 views
What is the output of the following code?#include <stdio.h int main() { int x = 10; int *p = &x; int q = &p; q = q + 4; *p = *p + 1; printf("%d %d", x, q); return 0; ...
6 6 votes
2 2 answers
300
300 views
GO Classes asked Jun 25
300 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) = a; p++; printf("%d %d %d", (*p)[0], *(*(p + 1)...
8 8 votes
3 3 answers
312
312 views
GO Classes asked Jun 25
312 views
What is the output of the following code?#include <stdio.h int main() { int a = 5, b = 9; int *p = &a; int q = &p; *p = *p + 2; *q = &b; q = q + 3; printf("%d %d %d", ...
8 8 votes
3 3 answers
384
384 views
GO Classes asked Jun 25
384 views
What is the output of the following code?#include <stdio.h int main() { int a [3] = { {2, 4, 6}, {8, 10, 12} }; printf("%d %d %d", a , *(*(a + 1) + 1), *(*a + 2)); retur...