UMBC CS 201, Spring 00
UMBC CMSC 201 Spring '00 CSEE | 201 | 201 S'00 | lectures | news | help

Structures with Pointers to Structures

Recall from a previous lecture we created a structure called PERSON as typedef struct person { char name[30]; int age; } PERSON; But now suppose that we want more than just a 30 (or is it 29??) character name. Suppose we want to be able to refer to the first name, last name and even middle initial separately. We could make another structure called NAME and use it inside of PERSON. We did something similar to this in an earlier lecture with POINT and LINE. typedef struct name { char firstName[20]; char middleInitial; char lastName[20]; } NAME; and now define PERSON as typedef struct person { NAME name; int age; } PERSON;

Recall the syntax

Now, given the following declaration

PERSON bob;

to what do the following expressions refer and what is their data type?
Answers listed below.

bob bob.name bob.name.firstName bob.name.lastName[5]

The memory

Given the declaration of PERSON bob; above, how does the compiler allocate memory?

All memory needed for the variable bob is contiguous, just as you would expect. (As an interesting exercise, write a short program to define the structures above and declare PERSON bob; and print the sizeof (PERSON) -- you'll be surprised at the answer).

But it's possible to create a different picture of memory. Recall that we can create pointers to structures. Can we have a member of a structure be a pointer to another structure? Of course.

Consider this definition of PERSON

typedef struct person { NAME *pName; int age; } What does the picture of memory for PERSON look like now?

Now the memory to hold the NAME is not part of PERSON. PERSON only has a pointer to a NAME. Where's the memory the hold the NAME? The memory for NAME must be malloc'd.

What's the syntax now?

Now that PERSON has a pointer to NAME, the syntax is different.
Given the declaration PERSON bob; What is the syntax for referring to a. bob's name b. bob's first name c. the 3rd character of bob's last name Answers below.


Answers to the first set of questions regarding PERSON bob
Answers to the questions regarding proper syntax.
If pName is a pointer to "struct NAME" then


CSEE | 201 | 201 S'00 | lectures | news | help

Wednesday, 19-Apr-2000 15:26:10 EDT