C Programming Basics
int m[3][4];
printf("%td\n", (char *)&m[2][1] - (char *)&m[0][0]);int is 4 bytes. Which of the following is the output when the code above is executed?
- A9
- B20
- C36
Show answer and explanation
Answer: C. 36
Two-dimensional arrays in C are stored in row-major order: m[3][4] is laid out as m[0][0] to m[0][3], m[1][0] to m[1][3], then m[2][0] to m[2][3]. Before m[2][1] there are 2 × 4 = 8 elements from two rows plus 1 in the same row, 9 elements in total. Each element is 4 bytes, so the distance from the start is 9 × 4 = 36 bytes. The subtraction is done after converting to char *, so the difference is expressed in bytes.
- A. This is the number of elements (9) without converting to bytes.
- B. This is the value obtained by assuming column-major order (stored column by column) ((1 × 3 + 2) × 4 = 20).
- C. Correct. (2 × 4 + 1) × 4 = 36 bytes.