Getting Inside a Structure

In Part 7-1 , we stated that we can not only see records as a single entity, but we can also look at individual components of records. In C (as in many other languages), we will use the operator dot ( . ) to identify a part of a structure we want to access. So for example, we might want to print the name of the student stored in the variable this_student . We could do this with the statement:
printf("%s", this_student.name);

Let us look carefully at the notation we've just used. The expression:


this_student

is of type struct student assuming the parameter declaration we saw in the previous part . Its value is the entire contents of that structure. The expression:
this_student.name

has the type pointer to a character and it's value is a pointer to the first character of the first member of the structure.

In general, we may construct expressions of the form:


structure.member

That is the dot operator expects a structure on the left and the name of a member of that structure on the right. Any expression of type structure can be used on the left as long as the structure it is includes a member of the name used on the right of the dot.

Let's look at an example of this:


#include <stdio.h>
struct student {
   char name[30];
   char address[60];
   int extension;
   int grad_year;
   float gpa;
};
void print_student(struct student this_student);
main()
{
   struct student new_student;
   scanf("%s", new_student.name);
   scanf("%s", new_student.address);
   scanf("%d", &new_student.extension);
   scanf("%d", &new_student.grad_year);
   scanf("%f", &new_student.gpa);
   print_student(new_student);
}
void print_student(struct student this_student)
{
   printf("Name: %s\n", this_student.name);
   printf("Address: %s\n", this_student.address);
   printf("Extension: %d\n", this_student.extension);
   printf("Grad Year: %d\n", this_student.grad_year);
   printf("GPA: %f\n", this_student.gpa);
}

Notice first that we put the structure declaration at the beginning where the function prototypes are. Also notice that in the scanf() statements we have used the format specifiers appropriate to each structure member as have we in the printf() statements. Likewise, we find that the ampersand ( & ) is used in scanf() for those members that are not already pointers, just as we've always done.
Given the declarations we've used above, which of the following represent valid integer expressions?

grad_year

new_student

this_student.extension

new_student.grad_year

student.grad_year