Which one of the choices given below would be printed when the following…

2006

Which one of the choices given below would be printed when the following program is executed? 

 #include
int a1[] = {6, 7, 8, 18, 34, 67};
int a2[] = {23, 56, 28, 29};
int a3[] = {-12, 27, -31};
int *x[] = {a1, a2, a3};
void print(int *a[])
{
            printf("%d,", a[0][2]);
            printf("%d,", *a[2]);
            printf("%d,", *++a[0]);
            printf("%d,", *(++a)[0]);
            printf("%d\\n", a[-1][+1]);
}
main()
{
             print(x);
}

  1. A.

    8, -12, 7, 23, 8

  2. B.

    8, 8, 7, 23, 7

  3. C.

    -12, -12, 27, -31, 23

  4. D.

    -12, -12, 27, -31, 56

Attempted by 95 students.

Show answer & explanation

Correct answer: A

Step-by-step evaluation:

  • Initial setup: the parameter a points to an array of pointers: a[0] -> a1 = {6,7,8,18,34,67}, a[1] -> a2 = {23,56,28,29}, a[2] -> a3 = {-12,27,-31}.

  • a[0][2]: a[0] is a1, so a1[2] = 8.

  • *a[2]: a[2] is a3, so *a[2] is a3[0] = -12.

  • *++a[0]: ++a[0] increments the pointer stored at a[0] (it changes from &a1[0] to &a1[1]); dereferencing yields a1[1] = 7.

  • *(++a)[0]: ++a advances the pointer-to-pointer a to point to the next pointer (so it now points at the original a[1], which is a2). Dereferencing and taking [0] gives a2[0] = 23.

  • a[-1][+1]: after ++a the pointer a points to the second pointer; a[-1] refers back to the first pointer slot, which was earlier modified to point to a1+1. So a[-1][+1] is *(a1+1 + 1) = a1[2] = 8.

Final output: 8, -12, 7, 23, 8

Explore the full course: Gate Guidance By Sanchit Sir