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?

  1. A9
  2. B20
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the code above, which concerns a char array holding a string, is executed?
  2. After the declarations above, one of the statements A "p = t;", B "*p = 'x';", C "q = t;" or D "*q = 'x';" is written. Which of the following is the combination that causes compile errors?
  3. Which of the following is the output when the program above, which uses an array of function pointers, is executed?
  4. fill and use are functions defined elsewhere. Which of the following is a problem with the function above?
  5. Which of the following is true about the pointer returned by the function make above?