Question
Consider the following two C code segments. and are one and two dimensional arrays of size and respectively, where . Assume that in both code segments, elements of are initialized to 0 and each element of array is initialized to . Further assume that when stored in main memory all elements of are in same main memory page frame.
Code Segment 1:
// initialize elements of Y to 0
// initialize elements X[i][j] of X to i + j
for (i = 0; i < n; i++)
Y[i] += X[0][i];
Code Segment 2:
// initialize elements of Y to 0
// initialize elements X[i][j] of X to i + j
for (i = 0; i < n; i++)
Y[i] += X[i][0];
Which of the following statements is/are correct?
S1: Final contents of array will be same in both code segments
S2: Elements of array accessed inside the for loop shown in code segment 1 are contiguous in main memory
S3: Elements of array accessed inside the for loop shown in code segment 2 are contiguous in main memory
Official answer and solution
- Official answer
- C
- From
- Official GATE 2015 answer key
Solution
Trace array values and memory layout in C (row-major order).
Evaluate Statement S1:
- In both segments, .
- Code Segment 1 accesses . So , giving .
- Code Segment 2 accesses . So , giving .
Since for all in both cases, the final contents of array are identical. Statement S1 is correct.
Evaluate Statement S2:
- In C, two-dimensional arrays are stored in row-major order: row 0 elements () occupy consecutive contiguous memory addresses.
- Code Segment 1 accesses for , which are adjacent elements in row 0.
Therefore, the elements accessed are contiguous in memory. Statement S2 is correct.
Evaluate Statement S3:
- Code Segment 2 accesses for , which are the first elements of successive rows.
- In row-major layout, is located elements after . These are not contiguous in memory (they have stride ). Statement S3 is incorrect.
Thus, only Statements S1 and S2 are correct (Option C).
C
Confusing row-major and column-major memory ordering, thinking that accessing along columns (X[i][0]) is contiguous.
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 3
- Question
- 40 of 65, printed as CS Q.30
- 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.