union in C: solved exercise to save memory

union in C: solved exercise to save memory

This exercise is scheduled for daily publication and follows the same didactic structure used across the site: clear statement, compilable code, and expected output.

Problem statement

Implement a practical example of the topic and validate the output in the console.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <stdio.h>

typedef union {
    int i;
    float f;
    char c;
} Dato;

int main(void) {
    Dato d;
    d.i = 65;
    printf("int: %d\n", d.i);
    d.c = 'A';
    printf("char: %c\n", d.c);
    printf("Tamano union: %zu\n", sizeof(Dato));
    return 0;
}

Expected output

1
2
int: 65
char: A

Common mistakes

  • Not validating input and standard-library return values.
  • Ignoring edge cases (buffers, limits, null pointers).
  • Skipping basic compile/run verification.

Practical use

Unions are used in communication protocols, type variants, and parsing low-level binary formats.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.