Structures

Often a given entity will have a number of properties you wish to record. For example, a student might have a name, a student number, various marks etc. or a car might have a colour, a model, a year of manufacture etc. It is convenient to store all this data in one place, rather than using separate variables for each item. Structures allow you to do this.

A structure is a user defined data type that can have several different entries in it. For instance, a programmer could create a student structure that would contain all the properties s/he wanted to record about students. An example of such a structure is declared below:

struct student 
{
    int age;
    int studentNumber;
    float averageGrade;
    char name[32];
};
You'll notice that the student structure has several different data types. In this case, two ints, a float and a string. The members of a structure are declared exactly the same way variables are declared in a C program.

Often a programmer will use structures in creating a new data type. For instance, there may be several students and each student's data should be represented using the same structure. To facilitate this, it is worth creating a new data type that can then be used repeatedly for each student.

The command typedef is used to create new data types. The general form of typedef is as follows:

typedef <variable type> <name of new type>;
To create a datatype based on a structure, the variable type is simply the structure definition. For instance, the following creates a new datatype STUDENT based on the above structure:
typedef struct student 
{
    int age;
    int studentNumber;
    float averageGrade;
    char name[32];
} STUDENT;

Once created, the new data type can be used like any other data type. To access individual members of the structure, the variable name is indicated, followed by a period and the name of the structure member that is being accessed. The following code demonstrates the use of structures:

#include <stdio.h>

typedef struct student 
{
    int age;
    int studentNumber;
    float averageGrade;
    char name[32];
} STUDENT;

int main()
{
    //create two STUDENT variables
    STUDENT mary, faith;

    float avg;

    //assign their ages
    mary.age = 14;
    faith.age = 16;

    //assign student numbers
    mary.studentNumber = 5678;
    faith.studentNumber = 5432;

    //assign their average grades
    mary.averageGrade = 73;
    faith.averageGrade = 62.3;

    //members of structures can be used in calculations like
    //normal variables
    avg = (mary.averageGrade + faith.averageGrade ) /2.0;   

    printf("Mary's student number is %d.\n", mary.studentNumber);

    return 0;

}

next


 home                      table of contents                      about