Structure in C allows us to create a complex data type. This new type can hold multiple values of different types. If you are familiar with enum in C, the syntax to define a structure will be easy for you.
We create structures with the keyword struct. Normally we create them in a separate header file. Another option is to define them in our .c files, outside of any function.
There are several ways to create variables of the struct type that you created. The first way is to list the variable names after the structure definition like this:
Now you can work with the three employee variables.
I like to separate the types and the variables, so I prefer the second way. After you define the structure, use its Tag and the keyword struct to create a variable:
struct Employee worker1;
Also, you can declare a pointer:
struct Employee* worker2;
To access a member of a structure in C we use the dot ‘.’ and the arrow ‘->’ operators.
A complex structure is such that contains at least one member of complex type – for instance another structure. Let’s take the address member from above. Instead of keeping it in a string field, we can define it like this:
or like this:
Here is how the information in this complex structure looks after I input and output it:
In C, by default the data in a structure is automatically padded. The padding is adding empty bytes in the memory in order to align the data. This is done for two reasons:
On most processor architectures data alignment is mandatory - for instance on processors with RISC architectures (ARM, MIPS…). Unaligned data is allowed on processors with CISC architecture (almost all desktop computers x86, x64..).
Here is how we define an example structure in C:
And here is how it really looks in the memory:
So the result of sizeof(struct A) is 12 Bytes.
We can optimize our structures, by sorting their members by size. This results in more efficient placement in the memory and less padding bytes. For instance, we can optimize the above definition like this:
Now only 1 byte padding is necessary at the end of the definition. In the memory it looks like this:
Now sizeof(struct A) returns 8 Bytes.
After most articles I provide you with the source of the examples. This time is no different, but I really urge you to look at them. You can download the zip, containing the source and header files from here: structure-in-c-examples.zip