Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept....

Preview:

Citation preview

Chapter 11Structure and Union Types

J. H. Wang (王正豪 ), Ph. D.

Assistant Professor

Dept. Computer Science and Information Engineering

National Taipei University of Technology

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-2

User-Defined Structure Types

• record – a collection of information about one data object

• A database is a collection of information stored in a computer’s memory or in a disk file. – a database is subdivided into records

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-3

Structure Type Definition

• Example– Name: Jupiter– Diameter: 142,800 km– Moons: 16– Orbit time: 11.9 yr– Rotation time: 9.925 hr

• structure type – a data type for a record composed of multiple

components

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-4

Structure Type Definition (Cont’d)

#define STRSIZ 10

typedef struct {char name[STRSIZ];double diameter; /* equatorial diameter in km */int moons; /* number of moons */double orbit_time, /* years to orbit sun once */rotation_time; /* hours to complete onerevolution on axis */

} planet_t;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-5

Structure Type Definition (Cont’d)

• A name chosen for a component of one structure may be the same as the name of a component of another structure or the same as the name of a variable.

• The typedef statement itself allocates no memory • A variable declaration is required to allocate

storage space for a structured data object– planet_t current_planet, previous_planet, blank_planet =

{"", 0, 0, 0, 0};

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-6

Structure Type Definition (Cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-7

Structure Type Definition (Cont’d)

• hierarchical structure – a structure containing components that are

structures

• Exampletypedef struct {

double diameter;planet_t planets[9];char galaxy[STRSIZ];

} solar_sys_t;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-8

Structure Type Definition (Cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-9

Manipulating Individual Components of a Structured Data Object

• direct component selection operator – a period placed between a structure type

variable and a component name to create a reference to the component

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-10

Figure 11.1 Assigning Values to Components

of Variable current_planet

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-11

Manipulating Individual Components of a Structured Data Object (Cont’d)

• printf("%s's equatorial diameter is %.1f km.\n", current_planet.name, current_planet.diameter);– Jupiter's equatorial diameter is 142800.0 km.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-12

Review of Operator Precedence

• In a generic expression containing two of the same operators in sequence:– operand1 op operand2 op operand3

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-13

Review of Operator Precedence (Cont’d)

• Left associativity – (operand1 op operand2) op operand3

• Right associativity– operand1 op (operand2 op operand3)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-14

Manipulating Whole Structures

• With no component selection operator refers to the entire structure– previous_planet = current_planet;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-15

Program Style Naming Convention for Types

• To help reduce confusion, choose user-defined type names ending in the suffix _t.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-16

Structure Type Data as Input and Output Parameters

• When a structured variable is passed as an input argument to a function, all of its component values are copied into the components of the function’s corresponding formal parameter.

• When such a variable is used as an output argument, the address-of operator must be applied.

• The equality and inequality operators cannot be applied to a structured type as a unit.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-17

Figure 11.2 Function with a Structured Input Parameter

• print_planet(current_planet);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-18

Figure 11.3 Function Comparing Two Structured Values for Equality

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-19

Figure 11.4 Function with a Structured Output Argument

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-20

Structure Type Data as Input and Output Parameters (Cont’d)

• In order to use scanf to store a value in one component of the structure whose address is in plnp, we must carry out the following steps (in order):

1. Follow the pointer in plnp to the structure.2. Select the component of interest.3. Unless this component is an array (e.g., component

name in Fig. 11.4), get its address to pass to scanf.

• &*plnp.diameter would attempt step 2 before step 1.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-21

Structure Type Data as Input and Output Parameters (Cont’d)

• indirect component selection operator – the character sequence -> placed between a

pointer variable and a component name creates a reference that follows the pointer to a structure and selects the component

• two expressions are equivalent.– (*structp).component – structp->component

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-22

Structure Type Data as Input and Output Parameters (Cont’d)

• result = scanf("%s%lf%d%lf%lf", plnp->name, &plnp->diameter, &plnp->moons, &plnp->orbit_time, &plnp->rotation_time);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-23

Figure 11.5 Data Areas of main and scan_planet during Execution of status = scan_planet (&current_planet);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-24

Structure Type Data as Input and Output Parameters (Cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-25

Functions Whose Result Values Are Structured

• The function does not return the address of the structure as it would with an array result; rather it returns the values of all components.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-26

Figure 11.6 Function get_planet Returning a Structured Result Type

• current_planet = get_planet();• However, scan_planet with its ability to return an integer

error code is the more generally useful function.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-27

Figure 11.7 Function to Compute an Updated Time Value

• typedef struct {int hour, minute, second;

} time_t;• time_now = new_time(time_now, secs);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-28

Figure 11.8 Structured Values as a Function Input Argument and as a Function Result

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-29

Abstract Data Type

• abstract data type (ADT) – a data type combined with a set of basic

operations

• We must also provide basic operations for manipulating our own data types.

• If we take the time to define enough basic operations for a structure type, we then find it possible to think about a related problem at a higher level of abstraction.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-30

Figure 11.9 Data Type planet_t and Basic Operations

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-31

Parallel Arrays and Arrays of Structures

• Parallel Arraysint id[50]; /* id numbers and */

double gpa[50]; /* gpa's of up to 50 students */

double x[NUM_PTS], /* (x,y) coordinates of */, y[NUM_PTS]; /* up to NUM_PTS points */

• Array of Structures– A more natural and convenient organization is

to group the information in a structure whose type we define.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-32

Parallel Arrays and Arrays of Structures (Cont’d)• Example

#define MAX_STU 50typedef struct {

int id;double gpa;

} student_t;. . .{student_t stulist[MAX_STU];

• Example#define NUM_PTS 10typedef struct {

double x, y;} point_t;. . .{point_t polygon[NUM_PTS];

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-33

Parallel Arrays and Arrays of Structures (Cont’d)

• stulist[0].id

• stulist[0].gpa

• for (i = 0; i < MAX_STU; ++i) scan_student(&stulist[i]);

• for (i = 0; i < MAX_STU; ++i) printf("%d\n", stulist[i].id);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-34

Figure 11.11 An Array of Structures

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-35

Union Types

• union – a data structure that overlays components in memory, allowing one

chunk of memory to be interpreted in multiple waystypedef union {

int wears_wig;char color[20];

} hair_t;hair_t hair_data;

• hair_data does not contain both wears_wig and color components, but either a wears_wig component referenced by hair_data.wears_wig, or a color component referenced by hair_data.color.

• The amount of memory is determined by the largest component of the union.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-36

Union Types (Cont’d)

• typedef struct {int bald;hair_t h;

} hair_info_t;• base our manipulation on the value of the bald

component• Referencing the appropriate union component is

always the programmer’s responsibility; C can do no checking of the validity of such a component reference.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-37

Figure 11.14 Function That Displays a Structure with a Union Type Component

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-38

Figure 11.15 Two Interpretations of Parameter hair

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-39

Figure 11.16 Program to Compute Area and Perimeter of Geometric Figures

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-40

Figure 11.16 Program to Compute Area and Perimeter of Geometric Figures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-41

Figure 11.16 Program to Compute Area and Perimeter of Geometric Figures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-42

Figure 11.16 Program to Compute Area and Perimeter of Geometric Figures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-43

Common Programming Errors

• Write your own type-specific equality and I/O functions.

• Place the union within another structure that contains a component whose value indicates which interpretation of the union is correct.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-44

Figure 11.10 Partial Implementation of Type and Operators for Complex Numbers

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-45

Figure 11.10 Partial Implementation of Type and Operators for Complex Numbers (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-46

Figure 11.10 Partial Implementation of Type and Operators for Complex Numbers (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-47

Figure 11.10 Partial Implementation of Type and Operators for Complex Numbers (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-48

Figure 11.10 Partial Implementation of Type and Operators for Complex Numbers (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-49

Figure 11.12 Universal Measurement Conversion Program Using an Array of Structures

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-50

Figure 11.12 Universal Measurement Conversion Program Using an Array of Structures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-51

Figure 11.12 Universal Measurement Conversion Program Using an Array of Structures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-52

Figure 11.12 Universal Measurement Conversion Program Using an Array of Structures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-53

Figure 11.12 Universal Measurement Conversion Program Using an Array of Structures (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 11-54

Figure 11.13 Data File and Sample Run of Measurement Conversion Program

Recommended