twitter
    Find out what I'm doing, Follow Me :)

Using Pointers And Structures Together

Load and display the file named struct3.c for an example of using pointers with structures. This program is identical to the last program except that it uses pointers for someof the operations.
 
main( )
{
struct {
char initial;
int age;
int grade;
} kids[12],*point;
int index;
for (index = 0;index < 12;index++) {
point = kids + index;
point->initial = ’A’ + index;
point->age = 16;
point->grade = 84;
}
kids[3].age = kids[5].age = 17;
kids[2].grade = kids[6].grade = 92;
kids[4].grade = 57;
for (index = 0;index < 12;index++) {
point = kids + index;
printf("%c is %d years old and got a grade of %d\n",
(*point).initial,kids[index].age,
point->grade);
}
}


The first difference shows up in the definition of variables following the structure definition. In this program we define a pointer named "point" which is defined as a pointer that points to the structure. It would be illegal to try to use this pointer to point to any other variable type. There is a very definite reason for this restriction in C as we have alluded to earlier and will review in the next few paragraphs.

The next difference is in the for loop where we use the pointer for accessing the data fields. Since "kids" is a pointer variable that points to the structure, we can define "point" in terms of "kids". The variable "kids" is a constant so it cannot be changed in value, but "point" is a pointer variable and can be assigned any value consistent with its being required to point to the structure. If we assign the value of "kids" to "point" then it should be clear that it will point to the first element of the array, a structure containing three fields.