cng 140 c programming (lecture set 10) spring 2006-2007 bozyigit/cng140 chapter 12 structures

48
CNG 140 C Programming (Lecture set 10) Spring 2006-2007 http://www. ceng . metu.edu.tr/~bozyigit/cng140 Chapter 12 Structures

Upload: dorothy-strickland

Post on 11-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140C Programming(Lecture set 10)

Spring 2006-2007http://www.ceng.metu.edu.tr/~bozyigit/cng140

Chapter 12Structures

Page 2: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 2

Structures: Objectives

• Single Structures

• Arrays of Structures

• Passing and Returning Structures

• Common Programming and Compiler Errors

Page 3: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 3

Introduction

• Each data item listed in the following table is an entity by itself, called a data field

• Together, all the data fields form a single unit called a record– In C, a record is referred to as a structure

Page 4: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 4

Fields and a Record

Name:Surname:StudentID:Department:Class:EmailAddress:TelNo:Address:

Page 5: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 5

Fields and a Record

Name: TayfunSurname: AkinStudentID:1475532Department: CNGClass:1EmailAddress: e147553TelNo: 03926612932Address: METU-NCC

Page 6: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 6

Introduction (continued)

• A structure’s form consists of the symbolic names, data types, and arrangement of individual data fields in the record

• The structure’s contents consist of the actual data stored in the symbolic names

Page 7: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 7

Single Structures

• Structure definition in C:struct{ int month; int day; int year;} birth;

– Reserves storage for the individual data items listed in the structure

– The three data items are the members of the structure

• Assigning actual data values to the data items of a structure is called populating the structure

Page 8: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 8

spacing of a structure definition is not rigid

Single Structures (continued)

Page 9: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 9

Single Structures (continued)

• Multiple variables can be defined in one statementstruct {int month; int day; int year;} birth, current;

• Creates two structures having the same form

• The form of the structure can have type name proceeding the variable names– The list of structure members must be preceded by a user-

selected structure type namestruct Date{ int month; int day; int year;};

• Date is the structure type name

Page 10: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 10

By convention the first letter of user-selected structure type names is uppercase

Single Structures (continued)

Page 11: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 11

Single Structures (continued)

• Initialization of structures follows the same rules as for the initialization of arrays:– struct Date birth = {12, 28, 1987};

• Structure members can be of any data typestruct PayRecord{ char name[20]; int idNum; double regRate; /* regular rate */ double otRate; /* overtime rate */};struct PayRecord employee = {"H. Price", 12387, 15.89, 25.50};

Page 12: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 12

Single Structures (continued)

• Advantage of structures is when the same structure type is used in a list many times

• Individual members can be arrays and structuresstruct{ char name[20]; struct Date birth;} person;

– Example: person.name[4]

Page 13: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 13

Arrays of Structures

• Structure is a powerful data structure when used with arrays.

• It would be possible to have heterogeneity in arrays which would otherwise be inconvenient…

Page 14: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 14

Arrays of Structures: example

Page 15: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 15

Arrays of Structures (continued)

Page 16: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 16

struct PayRecord

struct PayRecord /* construct a global structure type*/

{

int id;

char name[20];

double rate;

};

Page 17: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 17

Inner braces are not necessary

Arrays of Structures (continued)

Page 18: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 18

Arrays of Structures (continued)

• Without explicit initializers, the numeric elements of both static and external arrays or structures are initialized to 0 (or nulls)

Page 19: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 19

ExampleThis listing uses a structure type which is slightly different to PersonalData in that string pointers are used instead of arrays. This allows more convenient handling of real-life strings.

/*********************************************************//* *//* Structures Demo *//* *//*********************************************************/ /* Simple program to initialize some structures */ /* and to print them out again. Does no error */ /* checking, so be wary of string sizes etc.. */

#include <stdio.h>

#define NAMESIZE 30#define ADDRSIZE 80#define NOOFPERSONS 20#define NEWLINE() putchar('\n');

Page 20: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 20

Example: cont.

/*********************************************************/

typedef struct { char *Name; char *Address; int YearOfBirth; int MonthOfBirth; int DayOfBirth; }PersonDat;

/*********************************************************/

Page 21: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 21

Example : cont.main () /* Make some records */{ PersonDat record[NOOFPERSONS]; PersonDat PersonalDetails(); int person;printf ("Birth Records For Employees");printf ("\n---------------------------");printf ("\n\n");printf ("Enter data\n");for (person = 0; person < NOOFPERSONS; person++) { record[person] = PersonalDetails(); NEWLINE(); }DisplayRecords (record);}

Page 22: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 22

Example : cont./*********************************************************/PersonDat PersonalDetails() /* No error checking! */{ PersonDat dat;

char strbuff[ADDRSIZE], *malloc();printf ("Name :");dat.Name = malloc(NAMESIZE);strcpy (dat.Name,gets(strbuff));printf ("Address :");dat.Address = malloc(ADDRSIZE);strcpy (dat.Address,gets(strbuff));printf ("Year of birth:");dat.YearOfBirth = getint (1900,2007);printf ("Month of birth:");dat.MonthOfBirth = getint (1,12);printf ("Day of birth:");dat.DayOfBirth = getint(1,31);return (dat);

}

Page 23: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 23

Example : cont.

/**********************************************************/DisplayRecords (rec)PersonDat rec[NOOFPERSONS];{ int pers;

for (pers = 0; pers < NOOFPERSONS; pers++) { printf ("Name : %s\n", rec[pers].Name); printf ("Address : %s\n", rec[pers].Address); printf("Date of Birth: %1d/%1d/%1d\n",rec[pers].DayOfBirth, rec[pers].MonthOfBirth,rec[pers].YearOfBirth); NEWLINE(); }}

Page 24: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 24

Example : cont./* Toolkit */getint (a,b) /* return int between a and b */int a,b;{ int p, i = a - 1;for (p=0; ((a > i) || (i > b)); p++) { printf ("? : "); scanf ("%d",&i);

}return (i);}

Page 25: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 25

Passing Structures

• Individual structure members may be passed to a function in the same manner as any scalar variable– display(emp.idNum)– calcPay(emp.payRate,emp.hours);

• On most compilers, complete copies of all members of a structure can also be passed to a function by including the name of the structure as an argument to the called function– calcNet(emp);

Page 26: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 26

Pass by value

Passing Structures (continued)

Emp and temp are two different structures of the same type

Page 27: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 27

Passing and Returning Structures using by reference notation or pointer

• A structure can be passed by reference– calcNet(&emp);– double calcNet(struct Employee *pt)– (*pt).idNum or *pt->idNum

indicates that the address of the structure is retrieved before the element is fetched..

(*pt).x and *pt->x are the same thing

Page 28: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 28

Passing and Returning Structures: example

Page 29: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 29

Passing and Returning Structures (continued)

• ++ and -- can be applied to structures– ++pt->hours \\ adds 1 to the hours member

– (pt++)->hours \\increment the address after the hours is accessed

– (++pt)->hours \\ increment the address before accessing hours

Page 30: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 30

Passing and Returning Structures (continued)

Page 31: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 31

Returning Structures

Page 32: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 32

Returning Structures (continued)

Page 33: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 33

Exercise 12.3.4a,b

• Write a C function larger() that returns the later date of any two given dates in mm/dd/yyyy

Page 34: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 34

Exercise 12.3.4a,b/*

Description: 12.3 Exercise 4b

*/

#include <stdio.h>

struct Date

{

int month;

int day;

int year;

};

struct Date larger(struct Date , struct Date );

Page 35: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 35

Exercise 12.3.4a,bint main(){ /* use any two dates a and b

struct Date a = {10, 9, 2001};struct Date b = {11, 3, 2001};struct Date c;printf ( "Date a: %d/", a.month );printf ( "%d/%d\n", a.day, a.year );printf ( "\nDate b: %d/", b.month );printf ( "%d/%d\n", b.day, b.year );c = larger(a, b);printf ( "\nThe larger of these two Dates is %d/", c.month );printf ( "%d/%d\n", c.day, c.year );

return 0;}

Page 36: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 36

Exercise 12.3.4a,bstruct Date larger(struct Date date1, struct Date date2)

{

/* Assume that all months have 30 days and all years have 365 days */

long d1 = date1.day + 30*(date1.month-1) + 365*date1.year;

long d2 = date2.day + 30*(date2.month-1) + 365*date2.year;

if (d1 > d2)

return date1;

else

return date2;

}

Page 37: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 37

Unions

• A union is a data type that reserves the same area in memory for two or more variables

union{ char key; int num; double price;} val;

– Each of these types, but only one at a time, can actually be assigned to the union variable

– A union reserves sufficient memory locations to accommodate its largest member’s data type

Page 38: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 38

Unions (continued)

• Individual union members are accessed using the same notation as structure members

• Typically, a second variable keeps track of the current data type stored in the unionswitch(uType){ case ‘c’: printf("%c", val.key); break; case ‘i’: printf("%d", val.num); break; case ‘d’: printf("%f", val.price); break; default : printf("Invalid type : %c", uType);}

Page 39: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 39

Unions (continued)

• A type name can be associated with a union to create templatesunion DateTime{ long days; double time;};union DateTime first, second, *pt;

• Pointers to unions use the same notation as pointers to structures

• Unions may be members of structures and arrays; structures, arrays, and pointers may be members of unions

Page 40: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 40

Unions (continued)

struct{ char uType; union { char *text; double rate; } uTax;} flag;

• rate is referenced as flag.uTax.rate• The first character of the string whose address is

stored in the pointer text is accessed as *flag.uTax.text

Page 41: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 41

UNION

#define AUTO 1

#define BOAT 2

#define PLANE 3

#define SHIP 4

Page 42: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 42

UNION

struct automobile { /* structure for an automobile */

int tires;

int fenders;

int doors;

};

typedef struct { /* structure for a boat or ship */

int displacement;

char length;

} BOATDEF;

Page 43: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 43

UNIONstruct {

char vehicle; /* what type of vehicle */int weight; /* gross weight of vehicle */union { /* type-dependent data */

struct automobile car; /* part 1 of the union */BOATDEF boat; /* part 2 of the union */struct {char engines;int wingspan;} airplane; /* part 3 of the union */BOATDEF ship; /* part 4 of the union */

} vehicle_type;int value; /* value of vehicle in dollars */char owner[32]; /* owners name */

} ford, sun_fish, piper_cub; /* three variable structures */

Page 44: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 44

UNIONmain() {

ford.vehicle = AUTO;ford.weight = 2742; /* with a full gas tank */ford.vehicle_type.car.tires = 5; /* including the spares */ford.vehicle_type.car.doors = 2;sun_fish.value = 3742; /* trailer not included */sun_fish.vehicle_type.boat.length = 20;piper_cub.vehicle = PLANE;piper_cub.vehicle_type.airplane.wingspan = 27;if (ford.vehicle == AUTO) /* which it is in this case */printf("?The ford has %d tires./n",ford.vechicle_type.car.tires);if (piper_cub.vehicle == AUTO) /* which it is not in this case */printf("The plane has %d tires.\n",piper_cub.vechicle_type.car.tires);

}

Page 45: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 45

Common Programming Errors

• Attempting to use structures and unions, as complete entities, in relational expressions

• Assigning an incorrect address to a pointer that is a member of a structure or union

• Storing one data type in a union and accessing it by the wrong variable name can result in an error that is particularly troublesome to locate

Page 46: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 46

Common Compiler Errors

Page 47: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 47

Summary

• A structure allows individual variables to be grouped under a common variable name

• A structure type name can be used to create a generalized structure type describing the form and arrangement of elements in a structure

• Structures are particularly useful as elements of arrays

Page 48: CNG 140 C Programming (Lecture set 10) Spring 2006-2007 bozyigit/cng140 Chapter 12 Structures

CNG 140 C Programming 48

Summary (continued)

• Individual members of a structure are passed to a function in the manner appropriate to the data type of the member being passed

• Structure members can be any valid C data type, including structures, unions, arrays, and pointers

• Unions are declared in the same manner as structures