C pointer-to-array allocation — total bytes allocated when int is 2 bytes.\n\n#include<stdio.h>\n#include<stdlib.h>\n#define MAXROW 3\n#define MAXCOL 4\n\nint main()\n{\n int (p)[MAXCOL];\n p = (int ()[MAXCOL]) malloc(MAXROW * sizeof(*p));\n return 0;\n}\n\nAssume sizeof(int) = 2. How many bytes does malloc request?

Difficulty: Easy

Correct Answer: 24 bytes

Explanation:


Introduction / Context:
This problem tests computing total bytes allocated when using a pointer to an array type with malloc. It reinforces that sizeof(*p) represents the entire array object, not just a single element.


Given Data / Assumptions:

  • sizeof(int) = 2 bytes.
  • *p has type int[4].
  • We allocate MAXROW (3) blocks of type *p.


Concept / Approach:
sizeof(*p) = number_of_columns * sizeof(int) = 4 * 2 = 8 bytes. The malloc call requests MAXROW * sizeof(*p) = 3 * 8 = 24 bytes. The pointer type or casting does not change the size requested.


Step-by-Step Solution:

1) Determine size of one row: 4 ints * 2 bytes = 8 bytes.2) Multiply by number of rows: 3 * 8 = 24.3) malloc requests 24 bytes in total.


Verification / Alternative check:
Printing sizeof(*p) in code (as in the previous question) yields 8, confirming the per-row size. Multiplying by 3 confirms 24.


Why Other Options Are Wrong:

  • 56/128: Overestimates unrelated to the given dimensions.
  • 12: Would be 3 * 4, incorrectly using sizeof(int) instead of sizeof(*p).


Common Pitfalls:
Forgetting that *p is an entire array type and miscounting bytes by element instead of by row.


Final Answer:
24 bytes

More Questions from Memory Allocation

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion