In C structures, which of the following declarations is incorrect (identify the invalid one and explain why)? 1) struct aa { int a; float b; }; 2) struct aa { int a; float b; struct aa var; // member is a complete object of the same type }; 3) struct aa { int a; float b; struct aa *var; // pointer to same type };
-
A1
-
B2
-
C3
-
D1, 2, and 3
-
E1 and 3
Answer
Correct Answer: 2
Explanation
Introduction / Context:Self-referential structures enable linked lists and trees, but they must be written correctly. C permits pointers to an incomplete type within the same struct, but not a full instance of that same type as a member, because its size would be undefined (infinitely recursive).
Given Data / Assumptions:
- Three candidate declarations of a struct named aa.
- Standard C rules for complete vs. incomplete types apply.
- We are checking syntactic and semantic validity, not usage.
Concept / Approach:A struct type becomes complete at the closing brace of its definition. Inside the definition, the type is incomplete. C allows declaring pointers to an incomplete type (since pointer size is known) but not embedding a full object of that incomplete type (size unknown).
Step-by-Step Solution:Case 1: Plain fields only (int, float) → valid.Case 2: Member is struct aa var; but struct aa is incomplete within its own definition → invalid due to infinite recursion of size.Case 3: Member is struct aa *var; pointer size is known → valid.Therefore, only declaration (2) is incorrect.
Verification / Alternative check:Try compiling: (2) yields a diagnostic like “field has incomplete type,” whereas (3) compiles and is commonly used for linked structures.
Why Other Options Are Wrong:1: Standard, correct struct.3: Correct self-referential pointer usage.1, 2, and 3 / 1 and 3: contradict the analysis.
Common Pitfalls:Embedding the same struct type directly instead of a pointer; forgetting that mutual embedding of two structs also requires pointers or forward declarations.
Final Answer:2