<<

CSE 142 Concepts this lecture Computer Programming I Review: Data structures Heterogenous structures (structs, records) Structures struct type definitions (typedef) Field selection (. operator) Structs as parameters Or… Call by value There are more things in Heaven and Earth, Pointer parameters and -> operator C, than are dreamt of in your grammar.

S-1 S-2 © 2000 UW CSE

Chapter 11 Review: Data Structures Functions give us a way to organize programs. Read 11.1-11.3, & 11.7 Data structures are needed to organize data, especially: 1. large amounts of data 11.1: Structure types 2. variable amounts of data 11.2: Structures as parameters 3. sets of data where the individual pieces are related to one another 11.3: Structures as return values Arrays helped with points 1 and 2, but not with point 3 Optional examples; skim or read: Example: the data describing one house in a neighborhood: x, y, color, # windows, etc. 11.4: Complex numbers Example: information about one student: name, ID, GPA, etc. etc. S-3 S-4

Problem: Account Records Structs: Heterogeneous Structures Collection of values of possibly differing types. The Engulf & Devour Credit Co. Inc., Ltd. needs to keep track of insurance policies it has issued. Name the collection; name the components Information recorded for each policy (fields). Account number (integer) Example: Insurance policy information for Alice Policy holder’s age (integer) and sex (‘m’ or ‘f’) (informally) Monthly premium (double) “alice” C expressions: At E&G, customers are only known by their account 9501234 account #, so there is no need to store their age 23 alice.age is 23 names. sex 'f' alice.sex is 'f' premium 42.17

S-5 2*alice.premium is 84.34S-6

S-1 Defining structs Defining struct types There are several ways to define a struct typedef struct { /* record for one policy:*/ in a C program. For this course: int account; /* account number */ Define a new type specifying the fields int age; /* policy holder’s age */ in the struct char sex; /* policy holder’s sex */ Declare variables as needed using that double premium; /* monthly premium */ new type } account_record; The type is defined only once at the beginning of the program Defines a new data type called account_record. Variables with this new type can be Does not declare (create) any variables. No storage is declared as needed. allocated. S-7 S-8

Style Points in struct types Declaring struct Variables In a type definition, use comments to describe the fields, Follow the usual rules: not the contents of the fields for any write the type name followed by one or more particular variable variable identifiers I.e., describe the layout of an Only difference: this time the type is defined account_record, not information about by the programmer, not built in Alice’s account.

typedefs normally are placed at the top of the program file

S-9 S-10

Declaring struct Variables Field access alice /*typedef students_record A fundamental operation on goes at top of program */ account struct variables is field access: ... age struct_name.field_name sex selects the given field account_record alice; premium (variable) from the struct account_record bob; alice bob alice.age = 23; account_record is a type; alice.premium = 12.20; account alice and bob are variables. age 23 account alice.premium = 2 * age sex alice.premium; Both variables have the sex premium 12.20------24.40 same internal layout premium S-11 S-12

S-2 Field access Terminology alice A selected field is an ordinary variable - it can account The terms “struct”, “record” and “structure” be used in all the usual age mean the same thing ways sex premium “fields” are often called “components” or alice.age++; “members”. printf("Alice is %d years old\n", alice.age); scanf("%lf", &alice.premium);

S-13 S-14

Why use structs? Structs as User-Defined Types C provides a limited set of built-in types: int, Collect together values that are treated as a unit char, double (and variants of these not discussed (for compactness, readability, maintainability). in these lectures) Pointers introduced some new types typedef struct { typedef struct { Arrays further enrich the possible types available int hours, minutes; int dollars, cents; double seconds; But... the objects in the real world and in } money; } time; computer applications are often more complex than these types allow This is an example of “abstraction” With structs, we’re moving toward a way for programmers to define their own types. S-15 S-16

Some Limitations struct Assignment

Like arrays, there are some restrictions on how a Unlike arrays, entire structs can be copied in a struct can be used compared to a simple single operation. Don’t need to copy field-by- variable (int, double, etc.) field. Can’t compare (==, !=) two structs directly Can assign struct values with = Can have functions with struct result types, Can’t read or write an entire struct with and can use struct values in a return scanf/printf statement But you can do these things on individual fields

S-17 S-18

S-3 struct Assignment structs as Parameters A struct assignment account 46532 structs behave like all other non-array values copies all of the fields. If age 12 when used as function parameters dilbert is another sex m Can be call-by-value (copied) account_record, then premium 12.95 Can use as pointer parameters dilbert = bob; is equivalent to dilbert.account = bob bob.account; account 46532 dilbert.age = bob.age; age 12 dilbert.sex = bob.sex; sex m dilbert.premium = premium 12.95 S-19 S-20 bob.premium;

struct initializers Midpoint Example Revisited /* Given 2 endpoints of a line, “return” coordinates of midpoint */ A struct can be given an initial value when it is declared. List initial values for the fields in the void midpoint( double x1, double y1, (x2, y2) same order they appear in the struct typedef. double x2, double y2, double *midxp, double *midyp ) { account_record *midxp = (x1 + x2) / 2.0; = { 970142, 6, ’?’, 99.95 } ; *midyp = (y1 + y2) / 2.0; (x , y ) } 1 1 (x +x ) (y +y ) ()1 2 , 1 2 2 2 double ax, ay, bx, by, mx, my; S-21 midpoint(ax, ay, bx, by, &mx, &my); S-22

Points as structs Midpoint with points Better: use a struct to make the concept of a “point” explicit in the code /* return point whose coordinates are the center of the line segment with endpoints typedef struct { /* representation of a point */ pt1 and pt2. */ double x, y; /* x and y coordinates */ point midpoint (point pt1, point pt2) { point mid; } point; mid.x = ( pt1.x + pt2.x ) / 2.0; ... mid.y = ( pt1.y + pt2.y ) / 2.0; point a = {0.0, 0.0}, b = {5.0, 10.0}; return mid; point m; } m.x = (a.x + b.x) / 2.0; ... m.y = (a.y + b.y) / 2.0; point a = {0.0, 0.0}, b = {5.0, 10.0}, m; S-23 ... /* struct declaration and initializationS-24 */ m = midpoint (a, b); /* struct assignment */

S-4 Execution Midpoint with Pointers point midpoint ( point pt1, point pt2) { Instead of creating a temporary variable and point mid; x 0.0 x 5.0 x 2.5 returning a copy of it, we could write the function so mid.x = ( pt1.x + pt2.x ) / 2.0; it stores the midpoint coordinates directly in the mid.y = ( pt1.y + pt2.y ) / 2.0; y 0.0 y 10.0 y 5.0 destination variable. return mid; pt1 pt2 mid How? Use a pointer parameter: } ... midpoint void set_midpoint (point pt1, point pt2, point *mid) point a = {0.0, 0.0}, b = {5.0, 10.0}, m; x 0.0 x 5.0 x 2.5 point a = {0.0, 0.0}, b = {5.0, 10.0}, m; ... set_midpoint (a, b, &m); m = midpoint (a, b); y 0.0 y 10.0 y 5.0 abmS-25 Structs behave like all non-array types when S-26 used as parameters. main

Field Access via Pointers Midpoint with Pointers

Function set_midpoint needs to access the x and y /* Store in *mid the coordinates of the midpoint */ fields of its third parameter. How? /* of the line segment with endpoints pt1 and pt2 */ void set_midpoint (point pt1, point pt2, point *mid) void set_midpoint (point pt1, point pt2, point *mid) { … (*mid).x = ( pt1.x + pt2.x ) / 2.0; Field access requires two steps: (*mid).y = ( pt1.y + pt2.y ) / 2.0; 1) Dereference the pointer with * } 2) Select the desired field with . Technicality: field selection has higher precedence point a = {0.0, 0.0}, b = {5.0, 10.0}, m; than pointer dereference, so parentheses are set_midpoint (a, b, &m); S-27 S-28 needed: (*mid).x

Execution Pointer Shorthand: ->

void set_midpoint (point pt1, x 0.0 x 5.0 “Follow the pointer and select a field” is a very point pt2, point *mid) { common operation. C provides a shorthand (*mid).x = ( pt1.x + pt2.x ) / 2.0; y 0.0 y 10.0 operator to make this more convenient. (*mid).y = ( pt1.y + pt2.y ) / 2.0; pt1 pt2 mid } structp - > component ... set_midpoint point a = {0.0, 0.0}, means exactly the same thing as b = {5.0, 10.0}, m; ... (*structp).component 0.0 5.0 2.5 set_midpoint (a, b, &m); x x x y 0.0 y 10.0 y 5.0 -> is (sometimes) called the “indirect S-29 component selection operator” S-30 abm main

S-5 Pointer Shorthand: -> Summary

Function set_midpoint would normally be written Structs collect variables (“fields”) like this: possibly of differing types each field has a name /* Store in *mid the coordinates of the midpoint */ . operator used to access /* of the line segment with endpoints pt1 and pt2 */ void set_midpoint (point pt1, Struct fields follow the rules for their point pt2, point *mid) types { mid->x = ( pt1.x + pt2.x ) / 2.0; Whole structs can be assigned mid->y = ( pt1.y + pt2.y ) / 2.0; S-31 An important tool for organizing data S-32 }

QOTD: Frankenstein Types

You can now create a huge variety of types – pointers to things, arrays of things, structs containing all sorts of other things.

Create the wierdest, nastiest useful type you can imagine and show how you would access each part of that type.

Now, make a function with a pointer to your type as a parameter and show what you’d do! S-33 Need something more concrete? OK, your type should at least be a struct with an array of something inside it!

S-6