🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Declaring Structure Variables in C
Three ways to declare structure variables, how memory is really reserved, and why struct size can surprise you. Essential knowledge for embedded C programming.
In the previous lecture you wrote a structure definition and learned it is only a template. Now we make it useful. In this lecture of our free C programming course you will learn how to declare structure variables in C, why giving the structure a tag name is almost always the right choice, and how to measure exactly how many bytes a structure variable occupies using sizeof and offsetof.
The memory part is not optional trivia. In embedded C programming RAM is measured in kilobytes, and a carelessly ordered structure can quietly waste a third of its space. This free C tutorial shows you how to see that waste and remove it.
What You Will Learn
After this lecture you will be able to:
- Declare structure variables together with the definition, or separately using the tag.
- Explain why an anonymous structure limits you and show the compiler error it causes.
- Measure the size and member offsets of a structure with
sizeofandoffsetof. - Explain padding and alignment, and reorder members to shrink a structure.
Prerequisites
You should have finished Lecture 1 of this chapter: you need to know what a structure template is and that it reserves no memory. Basic knowledge of data type sizes (char, int, float) from the Elements of C chapter is also assumed.
Declaring Structure Variables: Two Ways
A definition only builds the format. Real use begins when you create variables from it. C gives you two ways to do that.
| Way | Example | Good for |
|---|---|---|
| Along with the definition | struct motor { int rpm; float amps; } m1, m2; | One-off variables, such as a single global state object |
| Using the tag later | struct motor m3; | Everything else; you can declare more variables anywhere the tag is visible |
Declaring Variables With the Definition
Place the variable names between the closing brace and the semicolon:
struct motor {
int rpm;
float amps;
} m1, m2;
Here m1 and m2 are both of type struct motor, and memory is reserved for each of them straight away. If the variables are declared outside any function they are global; inside a function they are local.
Declaring Variables Using the Structure Tag
Once struct motor is defined, you can create more variables whenever you need them, even in other functions:
struct motor m3;
struct motor spare, backup;
Remember that C requires the word struct every time. The tag alone, motor m3;, is an error in C.
Anonymous Structures and Why to Avoid Them
When you declare variables together with the definition, the tag name may be left out. This is an anonymous structure:
struct { int x; int y; } origin;
It works for origin, but the type has no name, so you can never declare another variable of that exact type later, never pass it to a function as a parameter, and never even assign one anonymous structure to another, because the compiler treats every anonymous definition as its own separate type. Look at this attempt:
int main(void)
{
struct { int x; int y; } p;
struct { int x; int y; } q;
p.x = 1; p.y = 2;
q = p; /* looks fine, but is not */
return 0;
}
error: incompatible types when assigning to type 'struct <anonymous>' from type 'struct <anonymous>'
Even though the two definitions are written identically, they are different types. The cure is simple: always give your structure a tag.
How Much Memory Does a Structure Variable Use?
Declaring a variable reserves space for every member, one after another, in the order you wrote them. A natural guess is that the size equals the sum of the member sizes. Often it does not, and the reason is alignment.
Processors read data most efficiently when a 4-byte integer starts at an address divisible by 4. To guarantee that, the compiler inserts invisible padding bytes between members when needed, and sometimes after the last one. Padding is never visible in your source code, but it is real memory.
Measuring With sizeof and offsetof
Two tools let you inspect the layout. sizeof gives the total bytes, and offsetof(type, member) from <stddef.h> gives the distance in bytes of a member from the start. Save this as ep_declare_styles.c:
#include <stdio.h>
#include <stddef.h>
struct motor { int rpm; float amps; } m1, m2; /* with the definition */
struct device_rec {
char name[20];
int id;
float volts;
};
struct pkt_a { char tag; int value; char flag; };
struct pkt_b { int value; char tag; char flag; };
int main(void)
{
struct motor m3; /* using the tag */
struct { int x; int y; } origin; /* anonymous */
struct device_rec d1;
m1.rpm = 1200; m2.rpm = 900; m3.rpm = 300;
origin.x = 0; origin.y = 0;
d1.id = 1;
printf("sizeof(m1) = %zu\n", sizeof(m1));
printf("sizeof(m3) = %zu\n", sizeof(m3));
printf("sizeof(origin) = %zu\n", sizeof(origin));
printf("--- struct device_rec layout ---\n");
printf("name offset %zu size %zu\n", offsetof(struct device_rec, name), sizeof d1.name);
printf("id offset %zu size %zu\n", offsetof(struct device_rec, id), sizeof d1.id);
printf("volts offset %zu size %zu\n", offsetof(struct device_rec, volts), sizeof d1.volts);
printf("total size = %zu\n", sizeof(struct device_rec));
printf("--- member order matters ---\n");
printf("pkt_a (char,int,char) = %zu\n", sizeof(struct pkt_a));
printf("pkt_b (int,char,char) = %zu\n", sizeof(struct pkt_b));
return 0;
}
Build and Run
$ gcc -std=c11 -Wall -Wextra -o ep_declare_styles ep_declare_styles.c
$ ./ep_declare_styles
Expected Output
sizeof(m1) = 8
sizeof(m3) = 8
sizeof(origin) = 8
--- struct device_rec layout ---
name offset 0 size 20
id offset 20 size 4
volts offset 24 size 4
total size = 28
--- member order matters ---
pkt_a (char,int,char) = 12
pkt_b (int,char,char) = 8
Why exactly 28 bytes?
The members of device_rec add up to 20 + 4 + 4 = 28, so no padding was needed: 20 is already divisible by 4, so id lands naturally at offset 20. Older textbooks often assume a 2-byte int and quote smaller totals; on today’s 32-bit and 64-bit targets, including ARM Cortex-M, int is 4 bytes, so always trust sizeof on your own compiler instead of counting by hand.
Byte layout of struct device_rec
| Offset | Member | Bytes |
|---|---|---|
| 0 to 19 | name[20] | 20 |
| 20 to 23 | id | 4 |
| 24 to 27 | volts | 4 |
Padding in Action: Member Order Matters
The last two lines of the output are the interesting ones. Both structures hold exactly the same members, one int and two chars, yet pkt_a takes 12 bytes and pkt_b takes 8. A third of pkt_a is padding.
Same members, different order, different size
| pkt_a offset | Content | Bytes |
|---|---|---|
| 0 | tag | 1 |
| 1 to 3 | padding | 3 |
| 4 to 7 | value | 4 |
| 8 | flag | 1 |
| 9 to 11 | tail padding | 3 |
| Total | 12 | |
| pkt_b offset | Content | Bytes |
|---|---|---|
| 0 to 3 | value | 4 |
| 4 | tag | 1 |
| 5 | flag | 1 |
| 6 to 7 | tail padding | 2 |
| Total | 8 | |
In pkt_a, the int cannot start at offset 1, so three bytes of padding push it to offset 4. The trailing char then needs three more bytes of tail padding, so that an array of these structures would keep every int aligned. In pkt_b the small members sit together after the int, leaving only two bytes of tail padding.
Rule of thumb: declare members from the largest type to the smallest. On a microcontroller with 20 KB of RAM and an array of a few hundred records, this one habit can save real memory.
Do not trust the padding in protocols. If a structure must match a byte layout defined by hardware or a network protocol, never assume there is no padding. Check it with sizeof and offsetof, or use your compiler’s packing feature deliberately. Packed structures can cause slow or faulty unaligned access on some processors, so use them only for data that really needs an exact layout.
Real-World Use Cases
- Global device state: one structure variable declared at file scope holds everything about a peripheral, such as
struct motor m1;. - Several identical devices: three motors, three variables, one tag.
- RAM budgeting: checking
sizeofat build time to make sure a record fits your memory plan.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Declaring motor m3; without struct | Unknown type name error | Write struct motor m3; |
| Using an anonymous structure for several variables | Incompatible types on assignment or in function calls | Give the structure a tag |
| Adding member sizes by hand | Wrong buffer size or wrong RAM estimate | Use sizeof on your target compiler |
| Ordering members randomly | Larger than needed structure | Largest members first |
Best Practices
- Always name the structure with a tag, then declare variables separately.
- Print
sizeofof important structures during development, and consider a compile-time check for sizes that must not change. - Order members by decreasing size unless a protocol dictates another order.
- Performance: well-aligned structures are read in a single memory access; misaligned ones can need extra cycles or even fault on strict architectures.
- Security: padding bytes hold unspecified values. Never send a whole structure over a network or write it to storage without clearing it first, or you may leak old memory contents.
Summary and Key Takeaways
Remember
- Variables can be declared with the definition or later with
struct tag name;. - Declaring a variable reserves memory; each variable gets its own copy of all members.
- Anonymous structures cannot be reused as a type; prefer a tag.
- The size of a structure can exceed the sum of its members because of padding.
- Use
sizeofandoffsetof, and order members largest first.
Conclusion
You can now create structure variables confidently and, more importantly, you know what the compiler does with memory behind the scenes. That awareness separates a beginner from someone ready for real embedded work. Next, we learn how to give these variables their first values with initialization, including the modern designated-initializer style used in professional firmware.
Frequently Asked Questions
How do I declare a structure variable in C?
Write struct tagname variable; after the definition, or list variable names right after the closing brace of the definition.
Is the tag name required?
No, but without it you cannot declare more variables of that type later or pass them cleanly to functions. Always use one.
Why is sizeof a structure bigger than the sum of its members?
The compiler adds padding bytes so each member starts at an aligned address.
How can I reduce the size of a structure?
Reorder members from largest to smallest type, so less padding is needed.
What does offsetof do?
It returns the number of bytes from the start of a structure to a given member, and is defined in stddef.h.
Do two variables of the same structure share memory?
No. Each variable has its own separate storage for every member.
Can I declare structure variables inside a function?
Yes. They become local variables, stored on the stack, and disappear when the function returns.
Where can I learn embedded C programming for free?
Right here. This free embedded C course on EmbeddedPathashala walks through every concept with tested examples.
Continue the Free C Tutorial
Next: initializing structure variables, partial initialization, and designated initializers.

2 Comments