C pointer-to-array allocation — total bytes allocated when int is 2 bytes.
#include
#include
#define MAXROW 3
#define MAXCOL 4
int main()
{
int (p)[MAXCOL];
p = (int ()[MAXCOL]) malloc(MAXROW * sizeof(*p));
return 0;
}
Assume sizeof(int) = 2. How many bytes does malloc request?
-
A56 bytes
-
B128 bytes
-
C24 bytes
-
D12 bytes
Answer
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