Pointer to Structures

Recall that the . symbol was used when specifying a particular entry in a structure. You can also have pointer to structures, but the syntax is slightly different. If you have a pointer to a structure, you use the -> symbol to specify a particular entry rather than the period. For example:

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

int main()
{
    //a STUDENT variable
    STUDENT mary;
    //a pointer to a STUDENT variable
    STUDENT * pupil; 

    //assign some values
    mary.age = 14;
    mary.studentNumber = 5678;
    mary.averageGrade = 73;

    //tell pupil to point at mary
    pupil = &mary;

    //Notice in the examples below the use of -> instead of .

    //we can now access members of the mary structure using the pupil pointer
    printf("Mary's student number is %d.\n", pupil->studentNumber);

    //we can also do assignment and all other normal variable operations
    pupil->averageGrade = 86.2;

    printf("Mary's average grade is %f.\n", mary.averageGrade);

    return 0;

}

next


 home                      table of contents                      about