In C, can a structure contain members of similar or dissimilar (heterogeneous) types?

Difficulty: Easy

Correct Answer: Correct — structures may mix unrelated types freely

Explanation:


Introduction / Context:
Structures in C are used to group related data, often of different types. This question checks awareness that structs are heterogeneous aggregates.


Given Data / Assumptions:

  • Standard C struct semantics.
  • Mixing types like int, char, double is common.


Concept / Approach:
A struct can hold fields of different types in sequence. The compiler arranges members with padding to meet alignment requirements; there is no constraint that members be identical types.


Step-by-Step Solution:
1) Define struct S { int id; char tag; double value; } — this is valid.2) The size reflects each member plus any padding.3) Access members using . or -> according to whether you have an object or a pointer.


Verification / Alternative check:
Checking sizeof(S) demonstrates inclusion of heterogeneous members and potential padding.


Why Other Options Are Wrong:
Option B: No single-type restriction exists.
Option C/D: Alignment and member count do not impose such limits.
Option E: The concept applies directly to C.


Common Pitfalls:
Ignoring padding when serializing structures or interfacing with hardware/ABI boundaries.


Final Answer:
Correct — structures may contain similar or dissimilar types.

More Questions from Structures, Unions, Enums

Discussion & Comments

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