C typedef and self-referential pointers: identify whether this declaration is valid. typedef struct data mystruct; struct data { int x; mystruct b; };
-
AError: in structure declaration
-
BLinker error
-
CNo error
-
DNone of the above
Answer
Correct Answer: No error
Explanation
Introduction / Context: This checks understanding of forward declarations with typedef and forming self-referential structures using pointers to an incomplete type, which is a common C pattern.
Given Data / Assumptions:
- A typedef name mystruct is introduced for struct data before its full definition.
- Inside struct data, a pointer of type mystruct is declared.
Concept / Approach: In C, it is legal to create a typedef to a yet-to-be-defined struct and then define the struct, using pointers to that incomplete type within the struct. Pointers to incomplete types are permitted; only complete type size is needed when allocating objects, not when declaring pointers.
Step-by-Step Solution:
typedef struct data mystruct; introduces mystruct as an alias for struct data (incomplete at this point).Define struct data { int x; mystruct *b; }; using a pointer to the incomplete type.This is valid since only a pointer is declared and the type becomes complete by the end of the definition.Verification / Alternative check: Compilers accept pointers to incomplete types within the type’s own definition; what is disallowed is having a struct contain a non-pointer instance of itself.
Why Other Options Are Wrong:
- Error in structure declaration: Not true; this is a standard idiom.
- Linker error: There is no unresolved symbol implied by this snippet.
- None of the above: Incorrect because “No error” is correct.
Common Pitfalls: Confusing incomplete types with invalid types, and forgetting the key rule that only pointers to the incomplete type are allowed within the definition, not the type itself as a member.
Final Answer: No error