Given char = 1 byte, int = 2 bytes, and long int = 4 bytes, will the structure below always occupy exactly 7 bytes? Explain considering alignment and padding. struct ex { char ch; int i; long int a; }

Difficulty: Medium

Correct Answer: No — due to alignment and padding, the structure typically occupies more than 7 bytes

Explanation:


Introduction / Context:
This question evaluates understanding of structure layout, alignment, and padding in C. Even when individual member sizes are known, the overall size must satisfy alignment constraints, which often introduces padding bytes.


Given Data / Assumptions:

  • char = 1 byte, int = 2 bytes, long int = 4 bytes.
  • Structure: struct ex { char ch; int i; long int a; }.
  • Conventional alignment: int aligned to 2, long aligned to 4 (typical).


Concept / Approach:
Members are placed in order. The compiler may insert padding so each member starts at an address multiple of its alignment. The structure size itself is also rounded up to a multiple of the strictest member alignment.


Step-by-Step Solution:
1) ch at offset 0 uses 1 byte.2) To align i (2-byte), 1 byte of padding is inserted so i starts at offset 2.3) i occupies 2 bytes (offsets 2–3), so next free offset is 4.4) a (4-byte) is naturally aligned at offset 4 and consumes 4 bytes (4–7).5) Total so far is 8 bytes, not 7, and it also satisfies 4-byte alignment of the largest member.


Verification / Alternative check:
Use sizeof(struct ex) on a target system with the stated sizes; it will typically report 8 bytes. Different ABIs may differ, but 7 is not generally achievable with standard alignment.


Why Other Options Are Wrong:
Option A/C/D/E: These ignore alignment rules; changing language mode, warnings, or operators does not alter layout and padding requirements.


Common Pitfalls:
Simply summing member sizes, forgetting padding between members, and ignoring final structure alignment to the largest member's requirement.


Final Answer:
No — alignment and padding mean the structure typically occupies 8 bytes, not 7.

More Questions from Structures, Unions, Enums

Discussion & Comments

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