ProgrammingHardProduct-company MCQ pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
int rows = 2, cols = 3;
int **matrix = malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++) matrix[i] = malloc(cols * sizeof(int));
for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        matrix[i][j] = i * cols + j;
printf("%d %d", matrix[1][2], *(*(matrix + 1) + 2));
  1. A. 5 5
  2. B. 4 5
  3. C. 5 4
  4. D. 4 4

Correct answer: A. 5 5

This is a true dynamically-allocated jagged array of pointers (NOT a contiguous 2D block): matrix[1][2] = 1*3+2 = 5. *(*(matrix+1)+2) is exactly the same access written in pointer-arithmetic form: matrix[1] gives the second row pointer, +2 then dereferenced gives the same element, 5.

More C Programming questions

Exams that ask this topic