Structs in C

2-minute read
Table of Contents

Structs are a way for us to group related data together in C. They can be used to make our code much more readable and relate entities in the code to more familiar objects.

Defining a struct

To define a struct, we give it a name (Person) and member variables (name, age and height):


struct Person{
    char name[100];
    int age;
    float height;
};

This is now a new custom datatype we can use. In the same way that in declaring a variable we would specify the datatype followed by the name of the variable, we write:


struct Person my_teacher;

Here the datatype is struct Person (telling the computer that we want a struct for a person) and the variable name/identifier is my_teacher.

Using typedef

Declaring a struct can be made even more readable by using typedef:


typedef struct Person Person;

The code can then be rewritten as:


Person my_teacher;

This can be read as us asking the computer to define a person called my_teacher;

Changing the value of member variables

We can then edit the member variables by using the struct’s identifier followed by . and the name of the member:


strcpy(my_teacher.name,"Joash");
my_teacher.age = 25;
my_teacher.height = 182;

Note how we need to use strcpy in order to change the value of a string member variable.

Support us via BuyMeACoffee