Extensive guide for Structures
For some reason a lot of people in my Group at Uni have quite a lot of problems with understanding concept and usage of Structs (structures) in C.
What structures are?!
They are basically compound types defined by the programmers. Imagine you want to model a Dog. Any dog has a name, an age and maybe favorite food. You would have to declare at least three variables to describe such a Dog for example in such a way:
What if you want to have more dogs?! Create multiple arrays and keep them in Sync? Even thinking about such solution is considered madness. (At least in my books) That’s exactly why structures were introduced into programming. They just couple some values together and allow you to access each of them individually. They are usually defined in headers. Their definition is pretty straight forward.
So it’s just few variables under one name? Exactly.. Knowing that we can easily declare our first struct. A dog.
I am using fixed size arrays just for convenience. Using pointers as fields may introduce some problems which I will try to cover a bit later.
Our first Struct
So we finally declared our first Struct. But that’s only description. How do we actually create a usable Dog?
We can also assign structures to each other.
And if we print each value individually we will see that corresponding values were indeed copied. But there is also a tiny little problem. C compiler is actually transpiling =
into shallow memory copy. You can read more about it here. It will be all fine unless you use a Structure or Pointer as a field.
The problem is that when you change b.pointer
the a.pointer
will also change… That’s why you should manually copy pointers that are members of structs to prevent that.