C pointers to arrays — sizes 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 printf("%d, %d\n", (int) sizeof(p), (int) sizeof(*p));\n return 0;\n}\n\nAssume sizeof(int) = 2. What is printed?

Difficulty: Medium

Correct Answer: 2, 8

Explanation:


Introduction / Context:
This question evaluates understanding of pointers to arrays and the difference between the size of a pointer and the size of the pointed-to object. The result depends on platform pointer size and known array dimensions.


Given Data / Assumptions:

  • sizeof(int) = 2 bytes.
  • p has type pointer to array of MAXCOL (4) ints.
  • Classic 16-bit near data pointer size of 2 bytes is assumed.


Concept / Approach:
sizeof(p) is the size of the pointer itself (near pointer, 2 bytes). sizeof(*p) is the size of the array it points to, which is 4 * sizeof(int) = 4 * 2 = 8 bytes. The malloc line allocates MAXROW arrays of 4 ints, but the printf only asks for the two sizes.


Step-by-Step Solution:

1) sizeof(p) = size of a near data pointer = 2.2) sizeof(*p) = size of int[4] = 4 * 2 = 8.3) Printed output therefore is "2, 8".


Verification / Alternative check:
On 32-bit systems, the first value would typically be 4, and on 64-bit systems 8, confirming platform dependence for pointer size only.


Why Other Options Are Wrong:

  • 4, 16 / 8, 24 / 16, 32: These correspond to different pointer sizes or wrong array-size calculations.


Common Pitfalls:
Confusing sizeof(p) with the size of allocated memory or forgetting that *p is an entire array, not a single int.


Final Answer:
2, 8

Discussion & Comments

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