🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Structures Explained Simply
Learn how a structure in C groups different data types under one name. A free C tutorial for embedded systems students, with a tested example you can build and run today.
Welcome to Chapter 10 of our free C programming course. So far every variable you created held one value, and every array held many values of the same type. Real programs rarely look like that. A temperature sensor has a name, an ID and a reading. A UART port has a baud rate, a parity setting and a timeout. C structures let you keep all of that together as one unit, and they are the single most important building block of embedded C programming: device drivers, protocol headers and hardware register maps are all written with them.
This lecture of our free embedded C course explains what a structure is, how to write its definition, what a definition does and does not do in memory, and where you are allowed to place it. Everything is explained from scratch and every program was compiled and run before it was put on this page.
What You Will Learn
By the end of this lecture you can:
- Explain why an array cannot store a name, an integer and a float together.
- Write the general syntax of a structure definition and name each part.
- State clearly that a definition is only a template and reserves no memory.
- Choose between a global and a local structure template and predict the compiler error for a wrong choice.
- Build and run your first C structure program and read its output.
Prerequisites
You should be comfortable with variables, data types (int, float, char), arrays, and printf. If character arrays still feel shaky, revisit the Strings chapter of this free C tutorial first. You need any C compiler; the examples use GCC with the C11 standard.
Why Arrays Are Not Enough
An array is a row of boxes where every box has the same type. That is perfect for 100 temperature readings, but useless when you want to describe one thing that has different kinds of properties. Imagine a small monitoring board with temperature nodes. For each node you must remember a label (text), an ID (integer) and the latest temperature (float).
Without structures you would create three parallel arrays and hope that index 4 in all three arrays always belongs to the same node:
char labels[10][12];
int ids[10];
float temps[10];
This works until you sort one array and forget the others, or until you want to pass one node to a function and must pass three separate arguments. The three pieces of data belong together, but the language does not know that. A structure tells the compiler exactly that.
One record made of three different types
What Is a Structure in C?
A structure is a user-defined data type that groups a fixed set of named pieces, called members, under a single name. The members may have different types, which is why a structure is called a heterogeneous data type. A member can be a plain number, an array, a pointer, or even another structure. Once you define a structure you get a brand new type, sitting right next to int and float, and you can create variables of that type.
Think of a structure as a printed form. The form has labelled fields, but a blank form holds no information. Only when you take a copy and fill it in do you have real data. The blank form is the structure definition; the filled-in copy is a structure variable.
Defining a Structure: Syntax
The general shape of a structure definition is:
struct tagname {
datatype member1;
datatype member2;
/* ... */
datatype memberN;
};
| Part | Meaning |
|---|---|
struct | Keyword that tells the compiler a structure is being described. |
tagname | The name of this new type. You use it later as struct tagname. |
| members | Declarations inside the braces, written exactly like normal variable declarations. |
; after } | Mandatory. Forgetting it is one of the most common beginner errors. |
Here is a concrete definition we will use through the next few lectures:
struct sensor_node {
char label[12];
int node_id;
float temp_c;
};
Now struct sensor_node is a type. Notice that the member declarations look like ordinary variable declarations, but they are not variables yet. This brings us to the most important idea in this lecture.
A Definition Reserves No Memory
When the compiler reads a structure definition it only records the format: which members exist, their types, and their order. It does not allocate a single byte for data. Memory is reserved only when you declare a variable of that structure type. Until then label, node_id and temp_c do not exist as storage anywhere.
Template versus variable
| Step | Code | Memory used |
|---|---|---|
| 1. Define the template | struct sensor_node { ... }; | None. Compiler only learns the layout. |
| 2. Declare a variable | struct sensor_node n1; | Space for all three members is reserved. |
| 3. Use the variable | n1.node_id = 7; | Data is stored in the reserved space. |
Because members are not variables, their names live inside the structure’s own namespace. Two members of one structure must have different names, but a member may reuse a name that exists outside the structure, and two different structures may even use the same member names. A member called id in a sensor structure and another id in a motor structure never clash.
Global or Local Structure Template?
A structure definition follows normal scope rules. If you write it above all functions it is global, so every function in the file can create variables of that type. If you write it inside a function it is local, and only that function can see it.
| Placement | Visible to | Typical use |
|---|---|---|
| Above all functions | Every function after it in the file | Data shared across functions; almost always what you want |
| Inside one function | Only that function | Small throwaway groupings used in one place |
See what happens when you define a structure inside one function and try to use it in another:
void declare(void)
{
struct local_cfg { int a; };
}
int main(void)
{
struct local_cfg c; /* main cannot see local_cfg */
c.a = 1;
return 0;
}
GCC refuses to compile this and reports:
error: storage size of 'c' isn't known
The message looks odd, but it simply means that, from main‘s point of view, struct local_cfg was never defined, so the compiler cannot know how big c should be. In real embedded projects structure definitions go into a header file so every source file shares one definition.
Your First Structure Program
Save this as ep_struct_intro.c. It defines the template globally, creates one variable, fills it in at declaration time, and prints it. Do not worry about the curly-brace initialization yet; Lecture 3 explains it in full.
#include <stdio.h>
/* Template only: no memory is reserved by this definition */
struct sensor_node {
char label[12];
int node_id;
float temp_c;
};
int main(void)
{
struct sensor_node n1 = { "boiler", 7, 81.5f };
printf("label : %s\n", n1.label);
printf("id : %d\n", n1.node_id);
printf("temp : %.1f C\n", n1.temp_c);
printf("sizeof(struct sensor_node) = %zu bytes\n", sizeof(struct sensor_node));
return 0;
}
Build and Run
$ gcc -std=c11 -Wall -Wextra -o ep_struct_intro ep_struct_intro.c
$ ./ep_struct_intro
Expected Output
label : boiler
id : 7
temp : 81.5 C
sizeof(struct sensor_node) = 20 bytes
The members add up to 12 + 4 + 4 = 20 bytes here. Lecture 2 shows that the total is not always the plain sum, because compilers sometimes insert hidden padding bytes.
Real-World Uses in Embedded Systems
- Peripheral configuration: one structure holds baud rate, parity and stop bits, and you pass it to an
initfunction. - Protocol frames: a header with a type, length and checksum maps naturally onto a structure.
- Hardware registers: vendor headers describe a whole peripheral as a structure whose members line up with consecutive registers.
- Device state: a driver keeps everything about one device instance, such as its ID, status and buffers, in a single structure. The Linux kernel is built around exactly this idea.
Common Mistakes and Troubleshooting
Watch out for these:
- Missing semicolon after the closing brace. The compiler usually complains at the next line, far from the real mistake.
- Using the tag as a variable.
sensor_node.temp_cis wrong becausesensor_nodeis a type, not a variable. You need a variable such asn1.temp_c. - Writing the keyword
structonly once. In C you must writestruct sensor_node n1;, notsensor_node n1;, unless you add atypedef(covered later in this chapter). - Defining the template inside a function and using it elsewhere. Move it to file scope or a header.
Best Practices
- Always give the structure a meaningful tag name; Lecture 2 shows what you lose without one.
- Put shared definitions in a header file so every source file sees the same layout.
- Use clear member names with units where it helps, such as
temp_cortimeout_ms. - Keep one structure focused on one idea. A structure that mixes unrelated data is hard to maintain.
- Performance note: a structure has no runtime cost of its own; accessing a member compiles down to a fixed offset from the variable’s address, the same work as indexing an array.
- Security note: character-array members have a fixed size. Always limit how much text you copy into them, otherwise you overflow into the neighbouring members.
Summary and Key Takeaways
Remember
- Arrays hold one type; structures group different types under one name.
- The pieces of a structure are called members; the type name is the tag.
- A definition is a template and uses no memory; a variable declaration reserves memory.
- Scope rules apply: global templates are visible everywhere, local ones only in their function.
- The closing brace must be followed by a semicolon.
Conclusion
You now know why structures exist and how to describe one. This is the foundation for everything else in this chapter and for reading real driver code. In the next lecture of this free embedded C course we will declare structure variables in several ways, see how much memory they actually occupy, and learn why reordering members can save bytes on a small microcontroller.
Frequently Asked Questions
What is a structure in C?
A structure is a user-defined type that groups several named members, possibly of different data types, under one name so they can be handled as one unit.
What is the difference between a structure and an array?
An array stores many elements of the same type and is accessed by index. A structure stores members of different types and is accessed by member name.
Does defining a structure use memory?
No. A definition is only a template. Memory is reserved when you declare a variable of that structure type.
Where should I define a structure in C?
Usually at file scope or in a header file so all functions can use it. Define it inside a function only if nothing else needs it.
Why is a semicolon needed after the closing brace?
Because the definition is a declaration statement, and it can also be followed by variable names. The semicolon ends that declaration.
Can a structure contain an array or another structure?
Yes. Members can be any type: arrays, pointers, or other structures that are already defined.
Are C structures used in embedded systems?
Constantly. Peripheral configuration, protocol headers, register maps and driver state are all commonly written as structures.
Is this C tutorial really free?
Yes. EmbeddedPathashala offers this free C programming course, including the embedded C material, with no sign-up.
Keep Going With the Free C Course
Next up: declaring structure variables and seeing exactly how many bytes they take. Explore the rest of our free embedded systems, free embedded Linux and free Linux device drivers courses too.

2 Comments