Question

What is the output of the following C code? Assume that the address of x is 20002000 (in decimal) and an integer requires four bytes of memory.

#include <stdio.h>

int main() {
    unsigned int x[4][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
        {10, 11, 12}
    };
    printf("%u, %u, %u", x + 3, *(x + 3), *(x + 2) + 3);
    return 0;
}
Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2015 answer key

Solution

Evaluate C 2D array expressions using pointer arithmetic scaling rules.

Given unsigned int x[4][3] with base address 20002000, where each unsigned int occupies 4 bytes4\text{ bytes}:

  • Each row contains 33 unsigned integers, occupying 3×4=12 bytes3 \times 4 = 12\text{ bytes}.
  • x has type unsigned int (*)[3] (pointer to an array of 3 ints).
  1. x + 3:
    Scales by the size of one row (12 bytes12\text{ bytes}):

    Address=2000+3×12=2000+36=2036.\text{Address} = 2000 + 3 \times 12 = 2000 + 36 = 2036.
  2. *(x + 3):
    Dereferences x + 3 to yield the 1D array x[3], which decays to a pointer to its first element &x[3][0].
    The numerical address of &x[3][0] is identical to the address of x[3]:

    Address=2036.\text{Address} = 2036.
  3. *(x + 2) + 3:
    *(x + 2) is x[2], which points to &x[2][0] at address 2000+2×12=20242000 + 2 \times 12 = 2024.
    Adding +3+3 advances by 33 elements of type unsigned int (4 bytes4\text{ bytes} each):

    Address=2024+3×4=2024+12=2036.\text{Address} = 2024 + 3 \times 4 = 2024 + 12 = 2036.

All three formatted values printed by printf are 2036, 2036, 2036 (option A).

Final answer

A

Common trap

Assuming *(x + 3) dereferences the value of the integer rather than decaying to a pointer.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
45 of 65, printed as CS Q.35
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.