Programming in C

(Barry) #1
Working with Pointers and Structures 241

struct date
{
int month;
int day;
int year;
};


Just as you defined variables to be of type struct date, as in


struct date todaysDate;


so can you define a variable to be a pointer to a struct datevariable:


struct date *datePtr;


The variable datePtr, as just defined, then can be used in the expected fashion. For
example, you can set it to point to todaysDatewith the assignment statement


datePtr = &todaysDate;


After such an assignment has been made, you then can indirectly access any of the mem-
bers of the datestructure pointed to by datePtrin the following way:


(*datePtr).day = 21;


This statement has the effect of setting the day of the datestructure pointed to by
datePtrto 21.The parentheses are required because the structure member
operator .has higher precedence than the indirection operator *.
To test the value of monthstored in the datestructure pointed to by datePtr,a
statement such as


if ( (*datePtr).month == 12 )
...


can be used.
Pointers to structures are so often used in C that a special operator exists in the lan-
guage.The structure pointer operator ->, which is the dash followed by the greater than
sign, permits expressions that would otherwise be written as


(*x).y


to be more clearly expressed as


x->y


So, the previous ifstatement can be conveniently written as


if ( datePtr->month == 12 )
...


Program 9.1, the first program that illustrated structures, was rewritten using the concept
of structure pointers, as shown in Program 11.4.

Free download pdf