UMBC CS 201, Fall 06
 UMBC CMSC 201 Fall '06 CSEE | 201 | 201 F'06 | lectures | news | help Search Notes:

# Structures and Pointers

### Pointers to members of structures

Since members of structures are variables, we can create pointers to them by using the & (address of) operator.

Recalling the structure definition of a struct point:

struct point { int x; int y; }; We could declare struct point point1, point2; int *pInt; and make pInt point to point2's x-coordinate with pInt = &point2.x; or we can pass the address of point2.x to a function printf ("Please enter the x-coordinate: "); scanf ("%d", &point2.x);

## Pointers to Structures

Since we can declare variables of some struct type (i.e. struct point point1;), we can create pointers to those variables. Once we have a pointer to the struct variable, we can access the members of that structure through that pointer. To accomplish this, we will use the "->" operator.

Here's an example:

struct student { char name; char major ; double gpa; }; struct student bob = {"Bob Smith", "Math", 3.77}; struct student sally = {"Sally", "CSEE", 4.0}; /* pstudent is a "pointer to struct student" */ struct student *pstudent; /* make pstudent point to bob */ pstudent = &bob; /* use -> to access the members */ printf ("Bob's name: %s\n", pstudent->name); printf ("Bob's gpa : %f\n", pstudent->gpa); /* make pstudent point to sally */ pstudent = &sally; printf ("Sally's name: %s\n", pstudent->name); printf ("Sally's gpa: %f\n", pstudent->gpa); Note too that the following are equivalent. Why?? pstudent->gpa and (*pstudent).gpa /* the parenthesis are necessary */

CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:17 EDT