C declarations: write a declaration for "A pointer to an array of three chars"

Difficulty: Medium

Correct Answer: char (*ptr)[3];

Explanation:


Introduction / Context:
This problem evaluates whether you can distinguish between “array of pointers” and “pointer to array” in C declarations. Arrays and pointers interact through decay in expressions, but their types are not interchangeable in declarations, and parentheses are essential to convey the correct binding.


Given Data / Assumptions:

  • We need a pointer to an array.
  • The array has exactly 3 elements.
  • Each element is of type char.


Concept / Approach:

The array type is “array of 3 char”, written char[3]. A pointer to that array type is written by putting parentheses around the identifier with the pointer declarator, yielding char (*ptr)[3]. The parentheses ensure that *ptr is evaluated before applying [3], so ptr is a pointer to a single array object of length 3, rather than an array of pointers or anything involving functions.


Step-by-Step Solution:

1) Start from the target object: an array of 3 char ⇒ char[3]. 2) Take a pointer to that array type ⇒ (*ptr) and then apply [3] to the type, not the variable. 3) Final form: char (*ptr)[3]. 4) Reading: ptr is a pointer to an array of three char.


Verification / Alternative check:

sizeof(*ptr) equals 3 * sizeof(char). Indexing (*ptr)[i] is valid for i in {0,1,2}. By contrast, char *ptr[3] declares an array of 3 pointers to char, which is a different type and storage layout entirely.


Why Other Options Are Wrong:

char *ptr[3]() — Introduces function declarators and describes an array of functions or function pointers, which is not required.

char (*ptr)*[3] — Invalid placement of declarators; not legal syntax.

char (*ptr[3])() — Declares an array of 3 pointers to functions, not a pointer to an array.


Common Pitfalls:

  • Omitting parentheses around *ptr and accidentally declaring an array of pointers.
  • Assuming pointer-to-array and array-of-pointers are interchangeable; they are not, and pointer arithmetic differs.


Final Answer:

char (*ptr)[3];

More Questions from Complicated Declarations

Discussion & Comments

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