In C, is it possible to create an array of pointers to structures?

Difficulty: Easy

Correct Answer: Correct — you can have arrays where each element is a pointer to a structure

Explanation:


Introduction / Context:
Arrays and pointers are core to C programming. Many real programs manage collections of dynamically allocated structures using arrays of pointers.


Given Data / Assumptions:

  • We have a user-defined structure type.
  • We may need multiple instances managed via pointers.


Concept / Approach:
C permits arrays of any object type, including pointer types. Therefore, an array of struct pointers is entirely valid and useful when objects are dynamically allocated and shared.


Step-by-Step Solution:
1) Declare struct Box { int w, h; };2) Declare struct Box *arr[10]; — an array of 10 pointers to Box.3) Allocate each element separately (e.g., malloc) and assign to arr[i].4) Access via arr[i]->w, arr[i]->h.


Verification / Alternative check:
Compile and run a small program that fills and reads from an array of struct pointers; it works portably.


Why Other Options Are Wrong:
Option B: Arrays can hold pointers. There is no such restriction.
Option C/D/E: These impose non-existent limitations on member makeup, scope, or length.


Common Pitfalls:
Forgetting to allocate or free each pointed-to object, and mixing up arr[i].member versus arr[i]->member.


Final Answer:
Correct — arrays of pointers to structures are fully supported.

More Questions from Structures, Unions, Enums

Discussion & Comments

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