Problem Solving and Program Design in C Chap. 11 Structure and Union Types Chow-Sing Lin
User-Defined Structure Types Define our own data types that represent structured collections of data pertaining to particular objects. Unlike array, a structure can have individual components that contain data of different types. Each of data items is stored in a separate component of the structure and can be referenced by using the component name. Database – A collection of information stored in a computer’s memory or in a disk – A database is subdivided into records, which normally contain information regarding specific data objects – The structure of the record is determined by the structure of the object’s data type Dr. Chow-Sing LinStructure and Union Types - CH112
Structure Type Definition Before a structured data object can be created or saved, the format of its components must be defined Defining a new data type for each category of structured objects Dr. Chow-Sing LinStructure and Union Types - CH113
Structure Type Definition (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH114 typedef struct { type 1 id_list 1 ; type 2 id_list 2 ; type n id_list n ; } struct_type; SYNTAX typedef struct { /* complex number structure */ double real_pt, imag_pt; } complex_t ; Example
Example 10.1 Develop a database of the planets in our solar system – We need to represent information Name: Jupiter Diameter: 142,800 km Moons: 16 Orbit: 11.9 yr Rotation time: hr Dr. Chow-Sing LinStructure and Union Types - CH115
Example 11.1 (Cont.) The structure type planet_t has five distinct components – Array of characters (string) – int – The other three are of type double Dr. Chow-Sing LinStructure and Union Types - CH116 #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*/ rotataion_time;/* hours to complete one revolution on axis*/ } planet_t;
Example 11.1 (Cont.) { planet_t current_planet, previous_plant, blank_plant = {“ ”,0,0,0,0}; ………. } Dr. Chow-Sing LinStructure and Union Types - CH117
Example 11.1 (Cont.) The variable blank_planet is pictured as it appears after initialization Dr. Chow-Sing LinStructure and Union Types - CH118 Variable blank_planet, a structure of type planet_t.name\0 ? ? ? ? ? ? ? ? ?.diameter0.0.moons 0.orbit_time0.0.rotation_time0.0
Example 10.1 (Cont.) Hierarchical structure – A structure containing component that are data structures (array or structs) Dr. Chow-Sing LinStructure and Union Types - CH119 typedef struct { double diameter; planet_tplanets[9]; chargalaxy[STRSIZ]; } solar_sys_t ;
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 Dr. Chow-Sing LinStructure and Union Types - CH1110
Example 10.2 Assigning Values to Components of Variable current_planet Dr. Chow-Sing LinStructure and Union Types - CH1111
Example 11.2 (Cont.) Once data are stored in a record – Can be manipulated in the same way as other data in memory Dr. Chow-Sing LinStructure and Union Types - CH1112 printf (“%s’s equatorial diameter is %.1f km. \n”, current_planet.name, current_planet.diameter ); Jupiter’s equatorial diameter is km. display
Review of Operator Precedence In a generic expression containing two of the same operators in sequence – operand 1 op operand 2 op operand 3 If op has left associatively (operand 1 op operand 2 ) op operand 3 If op has right associatively operand 1 op (operand 2 op operand 3 ) Dr. Chow-Sing LinStructure and Union Types - CH1113
Dr. Chow-Sing LinStructure and Union Types - CH1114 PrecedenceSymbolOperator NamesAssociatively a [ j ] f(…). Subscripting, function calls, direct component selection left Postfix increment and decrement left ! Prefix increment and decrement right - + & * logical not, unary negation and plus, address of, indirection (type name) Casts right * / % Multiplicative operators (multiplication, division, remainder) left + - Binary additive operators (addition and subtraction) left = Relational operators left == != Equality/inequality operators left && Logical and left || Logical or left = += -= *= /= %= Assignment operators right highest lowest
Manipulating Whole Structures The name of a structure type variable used with no component selection operator refers to the entire structure Make a new copy of a structure’s value Dr. Chow-Sing LinStructure and Union Types - CH1115 previous_planet = current_planet;
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 Dr. Chow-Sing LinStructure and Union Types - CH1116
Example 10.3 To display the value of structure current_planet print_planet(current_planet); Dr. Chow-Sing LinStructure and Union Types - CH1117
Structure type data as input and output parameters (Cont.) Function Comparing two structured values for equality – Returns 1 or 0 depending on whether all components match Dr. Chow-Sing LinStructure and Union Types - CH1118
Structure type data as input and output parameters (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1119 Return the value 1 if its single output argument is successfully filled Return the value 0 if there is an error Return the negative value EOF if the end of the file is encountered
Structure type data as input and output parameters (Cont.) Manipulating a structured output argument using operators “*” and “.” requires to keep operator-precedence rules (Table 10.1). – Direct component selection (.) has the highest precedence (LEFT) – &*plnp.diameter? Or &(*plnp).diameter? Dr. Chow-Sing LinStructure and Union Types - CH1120
Structure type data as input and output parameters (Cont.) In order to use scanf to store a value in one component of the structure whose address is in plnp – steps(in order) Follow the pointer in plnp to the structure Select the component of interest Unless this component is an array get its address to pass to scanf &*plnp.diameter &(*plnp).diameter Dr. Chow-Sing LinStructure and Union Types - CH1121
Structure type data as input and output parameters (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1122
Analysis of Reference &(*plnp).diameter Dr. Chow-Sing LinStructure and Union Types - CH1123 ReferenceTypeValue plnpplanet_t *address of structure that main refers to as current_planet *plnpplanet_tstructure that main refers to as current_planet (*plnp).diameterdouble &(*plnp).diameterdouble *Address of colored component of structure that main refers to as current_planet
Indirect component selection operator – “->” a minus sign followed by a greater-than symbol follows the pointer to a structure and selects the component (*structp).component == structp->component Dr. Chow-Sing LinStructure and Union Types - CH1124
Indirect component selection operator (Cont.) If we rewrite the scan_planet function of – Fig.10.4 using the “->” operator – the assignment to result will be Dr. Chow-Sing LinStructure and Union Types - CH1125 result = scanf (“%s%lf%d%lf%lf”, plnp->name, &plnp->diameter, &plnp->moons, &plnp->orbit_time, &plnp->rotation_time);
Functions whose result values are structured A function that computes a structured result can be modeled on a function computing a simple result A local variable of the structure type can be allocated, filled with the desired data, and returned as the function result The function does not return the address of the structure as it would with an array; rather is returns the values of all components Dr. Chow-Sing LinStructure and Union Types - CH1126
Functions whose result values are structured (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1127
Functions whose result values are structured (Cont.) Like function getchar, our function get_planet requires no arguments. If we assume entry of correct data, statement current_planet = get_planet(); has the same effect as scan_planet(¤t_planet); Example 10.5 Dr. Chow-Sing LinStructure and Union Types - CH1128
Problem Solving with Structure Types Abstract data type(ADT) – Combining a user-defined type with a set of basic operations – No longer bogged down in the details of manipulating the type’s components Dr. Chow-Sing LinStructure and Union Types - CH1129
Case Study A User-Defined Type for Complex Numbers – Develop a user-defined structure type and a set of operations – Make complex-arithmetic virtually as straightforward as arithmetic on C’s built-in numeric types Read Book Page 604~605 Code Page 606~611 Dr. Chow-Sing LinStructure and Union Types - CH1130
Dr. Chow-Sing LinStructure and Union Types - CH1131
Dr. Chow-Sing LinStructure and Union Types - CH1132
Dr. Chow-Sing LinStructure and Union Types - CH1133
Dr. Chow-Sing LinStructure and Union Types - CH1134
Dr. Chow-Sing LinStructure and Union Types - CH1135
Parallel Arrays and Arrays of Structures A data collection contains items of different types or items that, although of the same type, represent quite distinct concepts – For example The data used to represent a list of students might consist of – an integer identification number – a type double gpa for each student A polygon might be a list of the(x,y) coordinates of the polygon’s corners. Dr. Chow-Sing LinStructure and Union Types - CH1136
Parallel Arrays Array id and gpa are called parallel arrays int id[50]; /* id number and double gpa[50]; /* gpa’s of up to 50 students */ The ith elements of arrays x and y are the coordinates of one point double x[NUM_PTS], /* (x,y) coordinates of*/ double y[NUM_PTS]; /* up to NUM_PTS points*/ Dr. Chow-Sing LinStructure and Union Types - CH1137
Declaring an Array of Structures Group the information in a structure whose type we define Dr. Chow-Sing LinStructure and Union Types - CH1138 #define MAX_STU 50 #define NUM_PTS 10 typedef struct { int id; double gpa; } student_t; typedef struct { double x,y; } point_t; … { student_t stulist[MAX_STU]; point_t polygon[NUM_PTS];
Declaring an Array of Structures (cont.) Function scan_student is available for scanning a student_t structure – for statement can be used to fill the entire array stulist with data Dr. Chow-Sing LinStructure and Union Types - CH1139 for (i=0; i < MAX_STU; ++i) scan_student(&stulist[i]);
Case Study Universal Measurement Conversion – Spell-checks text and looks up synonyms for words – the conversion request 450 km miles – program output Attempting conversion of km to miles … km = miles Read Book Page 614~616 Code Page 617~622 Dr. Chow-Sing LinStructure and Union Types - CH1140
Dr. Chow-Sing LinStructure and Union Types - CH1141
Dr. Chow-Sing LinStructure and Union Types - CH1142
Dr. Chow-Sing LinStructure and Union Types - CH1143
Dr. Chow-Sing LinStructure and Union Types - CH1144
Dr. Chow-Sing LinStructure and Union Types - CH1145
Dr. Chow-Sing LinStructure and Union Types - CH1146
Union Types (Optional) So far, all variables we have seen of a particular structure type have had exactly the same components. Sometimes we need structured types in which some components vary depending on the value of another component. Union – a data structure that overlays components in memory – allowing one data object (a chunk of memory) to be interpreted in multiple ways Dr. Chow-Sing LinStructure and Union Types - CH1147
Example 10.6 define a union structure – use as the type of one component of a person’s physical description If the person has hair – record the hair color If the person is bald – note whether or not this baldness is disguised by a wig Dr. Chow-Sing LinStructure and Union Types - CH1148
Example 10.6 (Cont.) typedef statement allocates no memory declaration hair_t hair_data; – Creates a variable hair_data built on the template of the type definition – The variable hair_data has either a wears_wig component or a color component Dr. Chow-Sing LinStructure and Union Types - CH1149 typedef union { int wears_wig; char color[20]; } hair_t;
Example 10.6 (Cont.) When memory is allocated for hair_data – the amount of memory is determined by the largest component of the union a structure containing a hair_t union componet Dr. Chow-Sing LinStructure and Union Types - CH1150 typedef struct { int bald; hair_t h; } hair_info_t wears_wig color
Example 10.6 (Cont.) Function That Displays a Structure with a Union Type Component Dr. Chow-Sing LinStructure and Union Types - CH1151
Example 10.6 (Cont.) Two Interpretations of Parameter hair Dr. Chow-Sing LinStructure and Union Types - CH1152
Example 10.7 Hierarchical structure definition Dr. Chow-Sing LinStructure and Union Types - CH1153
1-54 Figure Program to Compute Area and Perimeter of Geometric Figures
1-55 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)
1-56 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)
1-57 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)