Structures can be used to do a “object-orientated” style of programming in C, a language which was originally designed to be functional.
Initialising structures is way of defining what the values of the variables inside the
struct will be at the time of creation. Note that there is a big syntax difference between initialising structures in C and in C++.
Unfortunately, you cannot define default variables for a structure when you declare it, only when you create an instance of that structure type. If this is annoying you, you might want to consider switching to C++, which allows you to do such a thing by using the class and constructor mechanisms.
You can easily copy a
struct in C with the assignment operator (
=). Although not the recommended method, you can also use
memcpy() to do the same thing.
Be careful, as passing in a
struct to a function will copy the entire structure, which is some cases might NOT be what you were expecting as:
- For a large struct, this could result in a lot of memory on the stack being used up.
- Any changes the function makes to the struct will not be seen from the calling function.
In these cases you what to pass in a pointer to the
You can self-reference a structure, but you cannot include the structure type in the structure itself (with would cause infinite recursion). To self-reference a structure, you have to use the little-used (in C anyway) name after typedef struct.
This work is licensed under a Creative Commons Attribution 4.0 International License .