In C (assume a typical little-endian system), what is the output of this program using a union to overlay int and char[2]? #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a u; u.ch[0] = 3; u.ch[1] = 2; printf("%d, %d, %d ", u.ch[0], u.ch[1], u.i); return 0; } Select the exact numbers printed.

Difficulty: Medium

Correct Answer: 3, 2, 515

Explanation:


Introduction / Context:
This problem evaluates understanding of C unions, memory overlay, and endianness. A union stores all members at the same location; writing one member and reading another reveals how bytes are arranged in memory. Most contemporary desktops use little-endian ordering, where the least significant byte is stored at the lowest address.



Given Data / Assumptions:

  • union a contains int i and char ch[2].
  • Assignments: ch[0] = 3 and ch[1] = 2.
  • Assume a little-endian machine and that sizeof(int) ≥ 2 bytes.
  • Reading u.i after writing the char bytes reflects the combined two bytes.


Concept / Approach:
In little-endian layout, ch[0] holds the least significant byte and ch[1] the next byte. Thus the integer value becomes 2 * 256 + 3 = 512 + 3 = 515. The first two printed values are exactly the assigned chars: 3 and 2.



Step-by-Step Solution:
Write low byte: ch[0] = 3.Write next byte: ch[1] = 2.Construct int (little-endian): i = 2 * 256 + 3 = 515.printf prints: 3, 2, 515.



Verification / Alternative check:
Test on an actual little-endian compiler or compute by byte combination: i = (ch[1] << 8) + ch[0] = (2 << 8) + 3 = 515.



Why Other Options Are Wrong:
515, 2, 3: reorders outputs incorrectly.3, 2, 5: treats 2 and 3 as digits rather than bytes.None of these: incorrect because 3, 2, 515 is correct.2, 3, 515: swaps the first two printed values.



Common Pitfalls:
Confusing big-endian vs little-endian; assuming chars are signed and letting sign extension distort reasoning (irrelevant here as we read the full int built from bytes).



Final Answer:
3, 2, 515

More Questions from Declarations and Initializations

Discussion & Comments

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