In C, may a structure contain a pointer to the same structure type (self-referential struct)?

C Programming Structures, Unions, Enums Difficulty: Easy
Choose an option
  • A
    Correct — self-referential structures via pointers are allowed (e.g., linked lists)
  • B
    Incorrect — a structure cannot mention its own type at all
  • C
    Allowed only if the pointer is declared as void *
  • D
    Allowed only at global scope, not inside functions
  • E
    Valid only when the structure has no other members

Answer

Correct Answer: Correct — self-referential structures via pointers are allowed (e.g., linked lists)

Explanation

Introduction / Context:Self-referential structures are fundamental for dynamic data structures such as linked lists, trees, and graphs. C supports this pattern via pointers.

Given Data / Assumptions:

  • We are defining a struct type.
  • We intend to include a pointer to the same struct type.

Concept / Approach:A struct cannot include a complete object of its own type (infinite size), but it can include a pointer to its own type because pointer size is fixed. This enables recursive data structures.

Step-by-Step Solution:1) struct Node { int data; struct Node *next; } is valid C.2) The pointer permits links between nodes without requiring the struct to know its total size in advance.3) Allocation happens dynamically (e.g., malloc) and nodes are chained via the pointer.

Verification / Alternative check:Compile a minimal linked-list node definition; it is universally accepted by C compilers.

Why Other Options Are Wrong:Option B: C permits referencing the same type via pointers.
Option C: No need to use void *; a typed self-pointer is preferred.
Option D: Scope does not limit this capability.
Option E: Other members are allowed alongside the pointer.

Common Pitfalls:Attempting to embed a complete instance (not a pointer) of the same struct type causes an incomplete type recursion error.

Final Answer:Correct — self-referential structures via pointers are allowed.

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