C Structures

C Structures


Structures

It appears to me, that very few people either use structures or know what they are and good for.

A structure creates a data type that can be used to group items of possibly different types into a single type.

Structures are more about readability. We can group variables that belong together. Let’s assume you need to handle someone’s address. Instead of having this:

void main() {  
        char street[50] = "Somestreet";  
        int housenumber = 123;  
        int postcode[5] = {4,3, 2, 1, 0};  
        char city[20] = "SomeCity";
}

We can group this into a structure. First, we have to declare the structure. We declare a structure that contains a street name, a house number, a 5-digit postcode, and a city.

struct address {
        char street[50];
        int housenumber;
        int postcode[5];
        char city[20];
};

Now we can define a variable in our main function, and initialize it like following:

void main() {
         struct address myAddress = {
                "SomeStreet",
                123,
                {1, 2, 3, 4, 5},
                "SomeCity"
        };
        printf("House Number: %u\n", myAddress.housenumber)
}

Which gives us House Number: 123.

Structures can be handled like any other variable. You can pass it into a function, build an array of structures, or nest structures in structures.

Structures are very useful to group data together. If you need to work with the data, i.e.,memcpy it will be much easier if you have them already grouped into a structure. But be careful: Structures might be bigger in the memory due to padding. But how does this work?

Memory Structure of ‘Structures’