1 epsii 59:006 spring 2004. 2 hw’s and solutions on webct

24
1 EPSII 59:006 Spring 2004

Upload: emil-grant

Post on 06-Jan-2018

215 views

Category:

Documents


1 download

DESCRIPTION

3 Introduction Structures  Collections of related variables (aggregates) under one name Can contain variables of different data types  Commonly used to define records to be stored in files  Combined with pointers, can create linked lists, stacks, queues, and trees

TRANSCRIPT

Page 1: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

1

EPSII

59:006Spring 2004

Page 2: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

2

HW’s and Solutions on WebCT

Page 3: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

3

Introduction

Structures Collections of related variables (aggregates) under one name

Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues,

and trees

Page 4: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

4

Structure Definitions Example

struct card { char *face; char *suit; };

struct introduces the definition for structure card card is the structure name and is used to declare variables of

the structure type card contains two members of type char *

These members are face and suit

Page 5: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

5

Structure Definitions struct information

A struct cannot contain an instance of itself Can contain a member that is a pointer to the same structure type A structure definition does not reserve space in memory

Instead creates a new data type used to declare structure variables

Declarations Declared like other variables, but using the struct keyword:

struct card oneCard, deck[ 52 ], *cPtr; Can use a comma separated list:

struct card { char *face; char *suit;} oneCard, deck[ 52 ], *cPtr;

Page 6: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

6

Structure Definitions

Valid Operations Assigning a structure to a structure of the same type Taking the address (&) of a structure Accessing the members of a structure Using the sizeof operator to determine the size of a structure

Page 7: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

7

Initializing Structures

Initializer lists Example:

struct card oneCard = { "Three", "Hearts" }; Assignment statements

Example:struct card threeHearts = oneCard;

Could also declare and initialize threeHearts as follows:struct card threeHearts;threeHearts.face = “Three”;threeHearts.suit = “Hearts”;

Page 8: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

8

Accessing Members of Structures

Accessing structure members (put on board) Dot operator (.) used with structure variables

struct card myCard = { "Three", "Hearts" };printf( "%s", myCard.suit );

Arrow operator (->) used with pointers to structure variablesstruct card *myCardPtr = &myCard;printf( "%s", myCardPtr->suit );

myCardPtr->suit is equivalent to( *myCardPtr ).suit

Page 9: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

9

Using Structures With Functions Passing structures to functions

Pass entire structure Or, pass individual members

Both pass call by value To pass structures call-by-reference

Pass its address Pass reference to it

To pass arrays call-by-value Create a structure with the array as a member Pass the structure

Page 10: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

10

typedef typedef

Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example:

typedef struct Card *CardPtr; Defines a new type name CardPtr as a synonym for type struct Card *

typedef does not create a new data type Only creates an alias Syntactically equivalent to a new data type, but only for the

program where you use it

Page 11: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

11

Example: High-Performance Card-shuffling and Dealing Simulation Pseudocode:

Create an array of card structures Put cards in the deck Shuffle the deck Deal the cards

Page 12: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

12

Load headers

Define struct

Function prototypes

Initialize deck[] and face[]

Initialize suit[]

1 /* Fig. 10.3: fig10_03.c2 The card shuffling and dealing program using structures */3 #include <stdio.h>4 #include <stdlib.h>5 #include <time.h>67 struct card { 8 const char *face;9 const char *suit;10 };1112 typedef struct card Card;1314 void fillDeck( Card * const, const char *[], 15 const char *[] );16 void shuffle( Card * const );17 void deal( const Card * const );1819 int main()20 { 21 Card deck[ 52 ];22 const char *face[] = { "Ace", "Deuce", "Three", 23 "Four", "Five",24 "Six", "Seven", "Eight", 25 "Nine", "Ten",26 "Jack", "Queen", "King"};27 const char *suit[] = { "Hearts", "Diamonds", 28 "Clubs", "Spades"};2930 srand( time( NULL ) );

Page 13: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

13

fillDeckShuffledeal

Function Definitions

3132 fillDeck( deck, face, suit );33 shuffle( deck );34 deal( deck );35 return 0;36 }3738 void fillDeck( Card * const wDeck, const char * wFace[], 39 const char * wSuit[] )40 { 41 int i;4243 for ( i = 0; i <= 51; i++ ) { 44 wDeck[ i ].face = wFace[ i % 13 ];45 wDeck[ i ].suit = wSuit[ i / 13 ];46 }47 }4849 void shuffle( Card * const wDeck )50 { 51 int i, j;52 Card temp;5354 for ( i = 0; i <= 51; i++ ) { 55 j = rand() % 52;56 temp = wDeck[ i ];57 wDeck[ i ] = wDeck[ j ];58 wDeck[ j ] = temp;59 }60 }

Put all 52 cards in the deck. face and suit determined by remainder (modulus).

Select random number between 0 and 51. Swap element i with that element.

Page 14: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

14

Function Definitions

6162 void deal( const Card * const wDeck )

63 { 64 int i;6566 for ( i = 0; i <= 51; i++ )

67 printf( "%5s of %-8s%c", wDeck[ i ].face, 68 wDeck[ i ].suit,69 ( i + 1 ) % 2 ? '\t' : '\n' );70 }

Cycle through array and print out data.

Page 15: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

15

Program Output

Eight of Diamonds Ace of HeartsEight of Clubs Five of SpadesSeven of Hearts Deuce of Diamonds Ace of Clubs Ten of DiamondsDeuce of Spades Six of DiamondsSeven of Spades Deuce of Clubs Jack of Clubs Ten of Spades King of Hearts Jack of DiamondsThree of Hearts Three of DiamondsThree of Clubs Nine of Clubs Ten of Hearts Deuce of Hearts Ten of Clubs Seven of Diamonds Six of Clubs Queen of Spades Six of Hearts Three of Spades Nine of Diamonds Ace of Diamonds Jack of Spades Five of Clubs King of Diamonds Seven of Clubs Nine of Spades Four of Hearts Six of Spades Eight of SpadesQueen of Diamonds Five of Diamonds Ace of Spades Nine of Hearts King of Clubs Five of Hearts King of Spades Four of DiamondsQueen of Hearts Eight of Hearts Four of Spades Jack of Hearts Four of Clubs Queen of Clubs

Page 16: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

16

Enumerations

User-defined data type Provide symbolic names for a range of

integer values Primary function is to improve program

readability

Page 17: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

17

Enumerations

enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

Example:

// sets JAN to 0, FEB to 1, … , DEC to 11)enum months month...for (month = JAN; month < =DEC; month ++) { …}

Page 18: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

18

/* Fig. 10.18: fig10_18.c Using an enumeration type */#include <stdio.h>

/* enumeration constants represent months of the year */enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

int main(){ enum months month; /* can contain any of the 12 months */

/* initialize array of pointers */ const char *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; /* loop through months */ for ( month = JAN; month <= DEC; month++ ) { printf( "%2d%11s\n", month, monthName[ month ] ); } /* end for */

return 0; /* indicates successful termination */} /* end main */

Enumeration Example

Note that the enumerationstarts at 1 rather than 0.

Page 19: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

19

Output./a.out 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September10 October11 November12 December

Page 20: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

20

Why Jan=1 ???

Just to illustrate that it can be done

Page 21: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

21

Enumerations—Some Caveats Variables declared to be of an enum type are really just

integers enum variables are not range checked—e.g consider the

following (nonsense) example:#include <stdio.h>main(){enum months {JAN, FEB, MAR};enum months mon;int i;mon = JAN;mon =13;i = FEB;

printf("mon = %d\n i = %d\n", mon, i);} mon = 13

i = 1

Note: no range checking

Can assign an enum constant to aninteger variable.

Page 22: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

22

Struct Example: Record

int age

struct record *next

char name[10]

struct Record

1

struct record *next

Bob

5

struct record *next

Tom

8

struct record *next

Fred

0

Page 23: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

23

struct Record { int age; // just a plain old int struct Record *next; // a pointer to another Record char name[10]; // plain old string };

main() { int i = 0; struct Record *p=0; // pointer to a Record

struct Record recs[100];

recs[0].age=1; recs[0].next=0; strcpy(recs[0].name,"Bob"); // what is wrong with // recs[0].name = "Bob";

recs[1].age=5; recs[1].next=0; strcpy(recs[1].name,"Tom");

recs[2].age=8; recs[2].next=0; strcpy(recs[2].name,"Fred");

for(i=0;i<=2;i++) { printf("age = %d name %s\n", recs[i].age,

recs[i].name); }

// Establishing links recs[0].next = &recs[1]; recs[1].next = &recs[2];

// another way to do loop p = &recs[0]; // set pointer to first Record while(p) { printf("age = %d name = %s\n",p->age,p-

>name); p = p->next; }

Page 24: 1 EPSII 59:006 Spring 2004. 2 HW’s and Solutions on WebCT

24

/* example showing structures and rudimentary linked list */

/* note, without dynamic memory allocation, linked list is */

/* problematic */

// Define a new "type" called "Record" -- analogous to "int"

// Record has 3 data types within it//struct Record { int age; // just a plain old int struct Record *next; // a ptr to another Record char name[10]; // plain old string };

main() { struct Record *p=0; // pointer to a Record

struct Record first = {1,0,"Bob"}; // first is a Record struct Record second = {5,0,"Tom"}; struct Record third = {8,0,"Fred"};

first.next = &second; // Establishing links second.next = &third; p = &first; // set pointer to first Record while(p) { printf("age = %d name = %s\n",p->age,p->name); p = p->next; } }