Presentation is loading. Please wait.

Presentation is loading. Please wait.

CNG 140 C Programming (Lecture set 10) Spring 2006-2007 Chapter 12 Structures.

Similar presentations


Presentation on theme: "CNG 140 C Programming (Lecture set 10) Spring 2006-2007 Chapter 12 Structures."— Presentation transcript:

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

2 CNG 140 C Programming2 Structures: Objectives Single Structures Arrays of Structures Passing and Returning Structures Common Programming and Compiler Errors

3 CNG 140 C Programming3 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

4 CNG 140 C Programming4 Fields and a Record Name: Surname: StudentID: Department: Class: EmailAddress: TelNo: Address:

5 CNG 140 C Programming5 Fields and a Record Name: Tayfun Surname: Akin StudentID:1475532 Department: CNG Class:1 EmailAddress: e147553 TelNo: 03926612932 Address: METU-NCC

6 CNG 140 C Programming6 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

7 CNG 140 C Programming7 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

8 CNG 140 C Programming8 spacing of a structure definition is not rigid Single Structures (continued)

9 CNG 140 C Programming9 Single Structures (continued) Multiple variables can be defined in one statement struct {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 name struct Date { int month; int day; int year; }; Date is the structure type name

10 CNG 140 C Programming10 By convention the first letter of user-selected structure type names is uppercase Single Structures (continued)

11 CNG 140 C Programming11 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 type struct PayRecord { char name[20]; int idNum; double regRate; /* regular rate */ double otRate; /* overtime rate */ }; struct PayRecord employee = {"H. Price", 12387, 15.89, 25.50};

12 CNG 140 C Programming12 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 structures struct { char name[20]; struct Date birth; } person; –Example: person.name[4]

13 CNG 140 C Programming13 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…

14 CNG 140 C Programming14 Arrays of Structures: example

15 CNG 140 C Programming15 Arrays of Structures (continued)

16 CNG 140 C Programming16 struct PayRecord struct PayRecord /* construct a global structure type*/ { int id; char name[20]; double rate; };

17 CNG 140 C Programming17 Inner braces are not necessary Arrays of Structures (continued)

18 CNG 140 C Programming18 Arrays of Structures (continued) Without explicit initializers, the numeric elements of both static and external arrays or structures are initialized to 0 (or nulls)

19 CNG 140 C Programming19 Example This 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 #define NAMESIZE 30 #define ADDRSIZE 80 #define NOOFPERSONS 20 #define NEWLINE() putchar('\n');

20 CNG 140 C Programming20 Example: cont. /*********************************************************/ typedef struct { char *Name; char *Address; int YearOfBirth; int MonthOfBirth; int DayOfBirth; } PersonDat; /*********************************************************/

21 CNG 140 C Programming21 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); }

22 CNG 140 C Programming22 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); }

23 CNG 140 C Programming23 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(); }

24 CNG 140 C Programming24 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); }

25 CNG 140 C Programming25 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);

26 CNG 140 C Programming26 Pass by value Passing Structures (continued) Emp and temp are two different structures of the same type

27 CNG 140 C Programming27 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

28 CNG 140 C Programming28 Passing and Returning Structures: example

29 CNG 140 C Programming29 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\\increment –(++pt)->hours \\ increment the address before accessing hours

30 CNG 140 C Programming30 Passing and Returning Structures (continued)

31 CNG 140 C Programming31 Returning Structures

32 CNG 140 C Programming32 Returning Structures (continued)

33 CNG 140 C Programming33 Exercise 12.3.4a,b Write a C function larger() that returns the later date of any two given dates in mm/dd/yyyy

34 CNG 140 C Programming34 Exercise 12.3.4a,b /* Description: 12.3 Exercise 4b */ #include struct Date { int month; int day; int year; }; struct Date larger(struct Date, struct Date );

35 CNG 140 C Programming35 Exercise 12.3.4a,b int 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; }

36 CNG 140 C Programming36 Exercise 12.3.4a,b struct 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; }

37 CNG 140 C Programming37 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

38 CNG 140 C Programming38 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 union switch(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); }

39 CNG 140 C Programming39 Unions (continued) A type name can be associated with a union to create templates union 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

40 CNG 140 C Programming40 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

41 CNG 140 C Programming41 UNION #define AUTO 1 #define BOAT 2 #define PLANE 3 #define SHIP 4

42 CNG 140 C Programming42 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;

43 CNG 140 C Programming43 UNION struct { 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 */

44 CNG 140 C Programming44 UNION main() { 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); }

45 CNG 140 C Programming45 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

46 CNG 140 C Programming46 Common Compiler Errors

47 CNG 140 C Programming47 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

48 CNG 140 C Programming48 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


Download ppt "CNG 140 C Programming (Lecture set 10) Spring 2006-2007 Chapter 12 Structures."

Similar presentations


Ads by Google