Structure in C Programming Complete Tutorial

  • Post author:
  • Post category:C

In this section, we will learn what the structure is and how to use it in C.

What is Structure in C?

Suppose we want to store a person’s information like her name, last name, phone, and id-number.

One solution is to create a variable for each of these data and store them in there.

For example:

int main() {

    char * name = "Ellen";
    char * lastName = "Cordon";
    int phone = 123456789;
    int id = 332442;
    

    return 0;
}

But what if we want to store the information of more people? Should we create more variables for each of these new data?

int main() {

    char * name = "Ellen";
    char * lastName = "Cordon";
    int phone = 123456789;
    int id = 332442;

    //**************
    char * name1 = "Barack";
    char * lastName1 = "Obama";
    int phone1 = 1234346273456789;
    int id1 = 3353453432442;
    //***************
    char * name2 = "Jack";
    char * lastName2 = "Bauer";
    int phone2 = 1223345234673289;
    int id2 = 332435442;

    return 0;
}

Well, as you can see, creating variable for each data in a program makes it a little hard to find the related data for each person!

For example, how do I know what’s the id number of `jack`? Which of these variables `id`, `id1`, `id2` is the one that holds the id number of `Barack`? Even if we want to change the id names to make them more convenient, it makes the naming variables more difficult than its usual.

Basically, there’s no clear structure here to follow!

This is where `structure` comes in.

A structure in C is used to create a compound data-type. For example, when we want to store the general information about a person, like her name, last name, email, etc. all in one place.

This is where the structure gives this ability to create a data-type that can store all these data in one place.

Struct Example in C:

#include <stdio.h>

struct person {
    char * name ;
    char * lastName ;
    int phone ;
    int id;
};

int main() {

    struct person ellen;
    ellen.name = "Ellen";
    ellen.lastName = "Cordon";
    ellen.phone = 2342341;
    ellen.id= 21;

    struct person obama;
    obama.name = "Barack";
    obama.lastName = "obama";
    obama.phone= 2312;
    obama.id= 3423;

    printf("%s",obama.name);
    return 0;
}

Output:

Barack

The purpose of this example is the same as what we had at the beginning of this section. We want to store the identity of a few people.

But as you can see, we didn’t create a variable like `name` or `phone` etc. to gather the related information of each person. Instead, we have created a data-type via `struct` keyword and named it `person` and within this structure we have declared any variable we need for each person.

Then, via the new data-type, we’ve created 2 variables and assigned a new identity to each variable.

Now we don’t need to create different variable for each data related to a person. For example, there’s no need to create two `name1, name2` etc.

Alright, now let’s get into the detail of how to build structures as well as declaring and initializing structure-variables:

How to Declare Structure in C? (Define a Struct in C)

This is how we can build a structure:

struct optional-name {
//declared fields…
};
  • `struct`: this is the keyword that should be present when we want to build a structure.
  • `Optional-name`: followed by the `struct` keyword is the name of the structure. All the rules that apply to a variable name also apply to union names as well.

You should know that the name is optional and we can simply skip that.

We mentioned that the name of a structure is the name of the data-type that later on in the program can be used to declare variables of this type. But we can simply skip the name and use the structure where we want to declare a variable.

Note: in such case the variable’s name should come after the closing brace of the structure.

Notes:

  1. Fields are actually variables, but because they are declared inside a structure, we call them fields and also structure member.
  2. Neither function-declaration nor variable-initialization is allowed in structure.

Example: creating struct in C

#include <stdio.h>

int main() {

    struct {
        char * name ;
        char * lastName ;
        int phone ;
        int id;
    } ellen;
    ellen.name = "Ellen";
    ellen.lastName = "Cordon";
    ellen.phone = 2342341;
    ellen.id= 21;


    printf("%s",ellen.name);
    return 0;
}

Output:

Ellen

As you can see, here we’ve created the structure right where the variable is declared.

The only problem here is the fact that the structure is no-longer can be used to build another variable out of it. (Of course, if we didn’t skip the name, we could use the structure to build other variables as well).

Example: Declaring Variables of Structure in C

#include <stdio.h>

int main() {

    struct person {
        char * name ;
        char * lastName ;
        int phone ;
        int id;
    } ellen;
    ellen.name = "Ellen";
    ellen.lastName = "Cordon";
    ellen.phone = 2342341;
    ellen.id= 21;

    struct person omid;
    omid.name = "Omid";
    printf("%s",omid.name);
    return 0;
}

Output:

Omid
  • `Body`: within a structure’s opening and closing curly-brackets, we can declare a number of fields that want to be used later for variables of the type of this structure.

Here’s an example of the wrong way of building a structure:

struct person {
    char * name = "Jack";
    char * lastName ="Bauer";
    int phone ;
    int id;
}

If you put this structure in a program and compile it, the compiler will return error because we’re trying to assign a value to a variable (AKA field).

Note: structures can be declared outside of any function, which in that case, their storage duration will be static and global scope, which means they can be accessible within any function for as long the program is running. Or they can be declared inside a function, which in that case, they are only accessible within the body of that function only.

Example: local struct in C

#include <stdio.h>

void printName(void);
int main() {

    struct person {
        char * name ;
        char * lastName ;
        int phone ;
        int id;
    };

    printName();
    return 0;
}
void printName(void){

    struct person ellen;
    ellen.name = "Ellen";
    ellen.lastName = "Cordon";
    ellen.phone = 2342341;
    ellen.id= 21;
}

Output:

error: storage size of 'ellen' isn't known

struct person ellen;

As you can see from the output, because we tried to access a local structure in another function, we’ve got the error mentioned above.

Declaration and initialization of structure-variables:

In order to declare a variable of structure type, we first use the keyword `struct` followed by that is the name of the structure and then is the variable name.

Example:

#include <stdio.h>


int main() {

    struct employee {
        char name[100] ;
        char lastName[100] ;
        int id;
    };
    struct employee ellen;
    
    return 0;
}

We can also initialize a variable right when declaring it.

Example:

#include <stdio.h>


int main() {

    struct employee {
        char name[100] ;
        char lastName[100] ;
        int id;
    };
    struct employee ellen= {"Ellen","Cordon",21};

    printf("%s %s %d\n",ellen.name, ellen.lastName,ellen.id);
    return 0;
}

Output:

Ellen Cordon 21

In order to initialize a variable of structure-type, we use braces `{}`and within the body of the braces we put the values for each field with the same order they’re declared in the body of that structure.

In this example, the first field declared in the body of the structure is the `name` which is of type char-array, and so we set the first value within the body of braces to “Ellen”. The second value is “Cordon” which will be assigned to the `lastName` and the last value is `21` which will be assigned to the `id` field.

Note: between each value we use comma `,` to separate them from each other.

Example: initialization of structs in C

There’s also another way of initializing a variable of structure-type and that is with the help of fields’ name, which will increase the clarity of value assignment to each field:

#include <stdio.h>


int main() {

    struct employee {
        char name[100] ;
        char lastName[100] ;
        int id;
    };
    struct employee ellen= {.nam= "Ellen",.lastName="Cordon",.id=21};

    printf("%s %s %d\n",ellen.name, ellen.lastName,ellen.id);
    return 0;
}

Output:

Ellen Cordon 21

In this example, as you can see, we used the name of fields + equal sign to assign values to each variable.

Note: when initializing a structure, before the name of each field, we need to use dot `.` as well.

How to use Structs in C? (Accessing Fields of Structures)

In order to access the fields of a structure-variable, we use:

The name of the structure-variable + dot + field’s name;

Example: using structs in C

#include <stdio.h>
struct employee {
    char *name ;
    char *lastName ;
    int id;
};
int main() {

    
    struct employee ellen;
    ellen.name = "Ellen";
    ellen.lastName = "Cordon";
    ellen.id = 21;
    printf("%s %s %d\n",ellen.name, ellen.lastName,ellen.id);
    return 0;
}

Output:

Ellen Cordon 21

As you can see, we first created a variable of employee-type named `ellen`. Then on the next lines, we accessed each field of this variable and assigned the right value to them.

Then on the last line, we called the name of each field in order to get their values and gave them to the `printf()` function in order to send the values to the output stream.

Nested Structures in C

We can also declare a structure within the body of another structure. This is known as a nested structure.

Example: creating nested structures in C

#include <stdio.h>
struct address{
    char * city;
    char * street;
    int zip;
};
struct employee {

    char *name ;
    char *lastName ;
    int id;
    struct address homeAddress;
};
int main() {


    struct employee ellen = {.name="Ellen",
            .lastName = "Cordon",
            .id= 21,
            .homeAddress= { .city = "xyz", .street = "fff", .zip = 321333}
    };

    printf("%s %s %d %s %s %d \n",ellen.name, ellen.lastName,ellen.id, ellen.homeAddress.city, ellen.homeAddress.street, ellen.homeAddress.zip );
    return 0;
}

Output:

Ellen Cordon 21 xyz fff 321333

When we want to initialize an inner-structure, we use the name of that inner-structure and, for its value, use braces and in that brace, the fields of this inner-structure will be initialized.

Note: names in this example are used for clarity and we know that it is possible to initialize fields without the use of their names.

Also, to access the field-names of an inner-structure, we need to use inner-structure name after the name of the structure-variable, just like the way we did in the example above.

Leave a Reply