🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Union Arrays Explained
Lecture 46 of our free C programming course: nested union access, union features, and arrays of unions for embedded C programming.
Chapter 10
Structure and Union
Level
Beginner to Intermediate
Reading time
12 minutes
A C union array lets you store a list of items where each slot may hold a different kind of value, while every slot costs only as much memory as its largest member. If you are following this free C programming course for embedded systems, you already know how a union shares one block of memory between its members. In this lecture we go one step further: we reach into unions that contain structures, review everything a union is allowed to do, and build arrays of unions the way real embedded C programming code does it for sensor logs, protocol frames and register images.
What You Will Learn
- How to access a structure that lives inside a union using the dot operator twice
- The five things a union can do, just like a structure
- How to declare and use a C union array and why its size is predictable
- How a tag field turns a union into a safe “variant” type
- Common mistakes and best practices for unions in embedded C
Prerequisites
You should be comfortable with structures (lectures cp10_1 to cp10_40), the dot operator, and the basic union definition from the previous lectures. A C99 or newer compiler such as gcc is enough to run every example here. This is part of the free embedded C course on EmbeddedPathashala, so no hardware is required.
Accessing a Structure Inside a Union
A union member can itself be a structure. When that happens, you use the dot operator once to pick the union member and a second time to pick the field inside the structure. Think of it as walking down a path: union variable, then member, then field.
Embedded engineers use this pattern constantly. A configuration word arrives from a peripheral as one 32-bit number, but your driver wants to read it as separate fields. The union gives you both views of the same bytes.
/* file: union_nested.c */
#include <stdio.h>
#include <stdint.h>
union device_cfg {
uint32_t word;
struct {
uint16_t timeout_ms;
uint8_t mode;
} fields;
};
int main(void)
{
union device_cfg cfg = { .word = 0 };
cfg.fields.timeout_ms = 500; /* union member, then structure field */
cfg.fields.mode = 3;
printf("timeout=%u mode=%u size=%zu\n",
cfg.fields.timeout_ms, cfg.fields.mode, sizeof cfg);
return 0;
}
Build and run it:
$ gcc -std=c11 -Wall -Wextra -o union_nested union_nested.c
$ ./union_nested
timeout=500 mode=3 size=4
Why size is 4 and not 3
The structure holds 2 + 1 = 3 bytes of data, but the compiler pads it to a multiple of its largest member alignment (2 bytes), giving 4 bytes. The union is then as big as its biggest member, which is also 4 bytes.
Five Things a C Union Array Can Do
A union is declared with the same syntax as a structure, and it gets almost all of the same abilities. The table below is worth memorising for exams and interviews.
| Feature | Allowed? | Embedded C use case |
|---|---|---|
| Array of unions | Yes | Mixed-type sample buffers |
| Union passed to or returned from a function | Yes (copied by value) | Returning a decoded register value |
| Pointer to a union | Yes | Walking a received packet buffer |
| Nested unions and structures | Yes, in both directions | Bit-field views of hardware registers |
| Self-referential union (pointer to its own type) | Yes, through a pointer | Tree or list nodes with variant payloads |
| Several members active at once | No | Only the last written member is safe to read as its own type |
Building a C Union Array
An array of unions is declared exactly like an array of any other type. Because every element is the size of the largest member, the array size is easy to predict: element count multiplied by sizeof of the union.
/* file: union_array.c */
#include <stdio.h>
#include <stdint.h>
union value {
int32_t i;
double d;
};
int main(void)
{
union value vals[3];
vals[0].i = 42;
vals[1].d = 2.5;
vals[2].i = -7;
printf("array size=%zu bytes, element size=%zu\n",
sizeof vals, sizeof vals[0]);
printf("%d %.1f %d\n", vals[0].i, vals[1].d, vals[2].i);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o union_array union_array.c
$ ./union_array
array size=24 bytes, element size=8
42 2.5 -7
Notice the problem hiding in this program: nothing in the array tells you which member of each slot is valid. If you read vals[1].i you would get meaningless bits. The compiler cannot protect you, so you must.
The Tag Field Pattern
The standard fix is to wrap the union in a structure together with a small enumeration called a tag. The tag records which member was written last. This is called a tagged union and it is how protocol parsers, interpreters and RTOS message queues stay safe.
/* file: tagged_sample.c */
#include <stdio.h>
#include <stdint.h>
enum kind { K_INT, K_FLOAT, K_BYTE };
struct sample {
enum kind kind;
union {
int32_t i;
float f;
uint8_t b;
} v;
};
static void show(const struct sample *s)
{
switch (s->kind) {
case K_INT: printf("int %d\n", s->v.i); break;
case K_FLOAT: printf("float %.2f\n", s->v.f); break;
case K_BYTE: printf("byte 0x%02X\n", s->v.b); break;
}
}
int main(void)
{
struct sample log[3] = {
{ K_INT, { .i = 1200 } },
{ K_FLOAT, { .f = 36.6f } },
{ K_BYTE, { .b = 0xA5 } },
};
for (int n = 0; n < 3; n++)
show(&log[n]);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o tagged_sample tagged_sample.c
$ ./tagged_sample
int 1200
float 36.60
byte 0xA5
C Union Array Uses in Embedded Systems
- Sensor logs: one buffer holds temperature (float), event counters (int) and status bytes without wasting RAM on three separate arrays.
- Message queues: an RTOS message is a tag plus a union of payload shapes.
- Register images: a 32-bit register is read once and then examined as named fields.
- Protocol frames: the same receive buffer is viewed as raw bytes or as a decoded header.
Common C Union Array Mistakes
Reading the wrong member. Writing vals[1].d and then printing vals[1].i gives garbage. Always keep a tag, or document the active member.
- Assuming a union array is smaller than it is: every slot is as big as the largest member.
- Forgetting that a union copied by value copies all bytes, including unused ones.
- Using a union to save a few bytes without measuring: padding inside nested structures can eat the savings.
- Comparing two unions with
==. The language does not allow it; compare the active members instead.
Best Practices
Union checklist
- Pair every shared-storage union with a tag when more than one member can be active over time.
- Use fixed-width types from stdint.h so sizes are the same on every target.
- Initialise unions with designated initialisers such as
{ .i = 5 }so the active member is obvious. - Print
sizeofduring bring-up to catch padding surprises early.
Summary and Key Takeaways
- Use the dot operator twice to reach a field of a structure nested inside a union.
- Unions support arrays, pointers, function arguments, return values, nesting and self-reference.
- A C union array has size count x sizeof(union), always set by the largest member.
- A tag field makes unions safe and is the pattern behind most real-world variant types.
In the next lectures you will see how unions help inspect bytes and detect machine byte order, a skill every embedded C programmer needs for communication protocols. Keep following this free embedded C course to build that knowledge step by step.
Frequently Asked Questions
How do I declare a C union array?
Yes. Declare it like any other array, for example union value vals[3];. Each element is as large as the biggest union member.
How big is a union array?
Element count multiplied by the size of one union. Check it with sizeof, because padding may make the union larger than its biggest scalar member.
How do I know which union member is valid?
C does not track it. Store a tag, usually an enum, next to the union and update it every time you write a member.
Can a union contain a structure?
Yes. Access it with two dot operators, for example cfg.fields.mode.
Can a function return a union?
Yes. The whole union is copied to the caller, just like a structure.
Are unions used in embedded C programming?
Very often: register overlays, protocol frames, message payloads and memory-constrained data buffers all use them.
Continue the Free C Programming Course
Learn C for embedded systems step by step with free tutorials, examples and quizzes on EmbeddedPathashala.

2 Comments