Question
What is the output of the following C code? Assume that the address of x is (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;
}
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 , where each unsigned int occupies :
- Each row contains unsigned integers, occupying .
xhas typeunsigned int (*)[3](pointer to an array of 3 ints).
-
x + 3:
Scales by the size of one row (): -
*(x + 3):
Dereferencesx + 3to yield the 1D arrayx[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 ofx[3]: -
*(x + 2) + 3:
*(x + 2)isx[2], which points to&x[2][0]at address .
Adding advances by elements of typeunsigned int( each):
All three formatted values printed by printf are 2036, 2036, 2036 (option A).
A
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.