281 views
9 9 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int a[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    int (*p)[3] = a;

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

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

2 Answers

2 2 votes


Here,

$\texttt{int (*p)[3] = a;}$

means $\texttt{p}$ is a pointer to an array of $\texttt{3}$ integers.

So, $\texttt{p}$ points to the first row of the 2D array.

The array is:

$\texttt{a[0][0] = 1}$, $\texttt{a[0][1] = 2}$, $\texttt{a[0][2] = 3}$

$\texttt{a[1][0] = 4}$, $\texttt{a[1][1] = 5}$, $\texttt{a[1][2] = 6}$

Now,

$\texttt{**p}$

means first row, first element.

So,

$\texttt{**p = a[0][0] = 1}$

Next,

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

Here, $\texttt{p + 1}$ moves to the second row.

So,

$\texttt{*(p + 1)}$ represents row $\texttt{1}$.

Then,

$\texttt{*(p + 1) + 2}$ points to $\texttt{a[1][2]}$.

So,

$\texttt{((p + 1) + 2) = a[1][2] = 6}$

Next,

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

Here, $\texttt{*p}$ represents the first row.

So,

$\texttt{*p + 1}$ points to $\texttt{a[0][1]}$.

Therefore,

$\texttt{*(*p + 1) = a[0][1] = 2}$
 

$\therefore$ Output : $\texttt{1 6 2}$
 

Answer: B

edited by
Answer:
Position:
Show:

Related questions

10 10 votes
1 1 answer
212
212 views
GO Classes asked Jun 20
212 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
211
211 views
GO Classes asked Jun 20
211 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
310
310 views
GO Classes asked Jun 20
310 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
220
220 views
GO Classes asked Jun 20
220 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)...