C programming — evaluate this self-referential structure declaration for correctness.\n\nstruct emp\n{\n int ecode;\n struct emp e; / pointer to the same struct type (self-reference) */\n};\n\nIs there any language error in the declaration above?

Difficulty: Easy

Correct Answer: No error

Explanation:


Introduction / Context:
Self-referential structures are common in linked lists and trees. The question checks whether a struct can contain a pointer to its own type within its definition.


Given Data / Assumptions:

  • The member e is declared as struct emp *.
  • No storage is allocated yet; only the type layout is set.


Concept / Approach:
C permits a struct to contain pointers to its own (incomplete) type in the same declaration. What is not permitted is embedding an instance (by value) of the same struct inside itself, which would make the size infinite. Pointers are fixed-size and therefore allowed.


Step-by-Step Solution:

1) During the struct's declaration, the tag struct emp becomes known.2) A pointer to struct emp is a complete type size-wise, even if the pointed-to type is incomplete.3) Therefore the declaration is valid; no compile-time error occurs.


Verification / Alternative check:
This pattern underlies singly and doubly linked lists. Code that later allocates nodes and links e to other struct emp values compiles and runs normally.


Why Other Options Are Wrong:

  • Structure declaration error: Incorrect; this is the idiomatic style.
  • Linker error: There is no external symbol involved here.
  • Undefined behavior: Only occurs if you dereference an uninitialized pointer at runtime, not from the declaration itself.


Common Pitfalls:
Confusing self-referential pointers (valid) with embedding the struct by value (invalid).


Final Answer:
No error

More Questions from Structures, Unions, Enums

Discussion & Comments

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