CNG 140 C Programming (Lecture set 10) Spring Chapter 12 Structures
CNG 140 C Programming2 Structures: Objectives Single Structures Arrays of Structures Passing and Returning Structures Common Programming and Compiler Errors
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
CNG 140 C Programming4 Fields and a Record Name: Surname: StudentID: Department: Class: Address: TelNo: Address:
CNG 140 C Programming5 Fields and a Record Name: Tayfun Surname: Akin StudentID: Department: CNG Class:1 Address: e TelNo: Address: METU-NCC
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
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
CNG 140 C Programming8 spacing of a structure definition is not rigid Single Structures (continued)
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
CNG 140 C Programming10 By convention the first letter of user-selected structure type names is uppercase Single Structures (continued)
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};
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]
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…
CNG 140 C Programming14 Arrays of Structures: example
CNG 140 C Programming15 Arrays of Structures (continued)
CNG 140 C Programming16 struct PayRecord struct PayRecord /* construct a global structure type*/ { int id; char name[20]; double rate; };
CNG 140 C Programming17 Inner braces are not necessary Arrays of Structures (continued)
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)
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');
CNG 140 C Programming20 Example: cont. /*********************************************************/ typedef struct { char *Name; char *Address; int YearOfBirth; int MonthOfBirth; int DayOfBirth; } PersonDat; /*********************************************************/
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); }
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); }
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(); }
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); }
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);
CNG 140 C Programming26 Pass by value Passing Structures (continued) Emp and temp are two different structures of the same type
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
CNG 140 C Programming28 Passing and Returning Structures: example
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
CNG 140 C Programming30 Passing and Returning Structures (continued)
CNG 140 C Programming31 Returning Structures
CNG 140 C Programming32 Returning Structures (continued)
CNG 140 C Programming33 Exercise a,b Write a C function larger() that returns the later date of any two given dates in mm/dd/yyyy
CNG 140 C Programming34 Exercise a,b /* Description: 12.3 Exercise 4b */ #include struct Date { int month; int day; int year; }; struct Date larger(struct Date, struct Date );
CNG 140 C Programming35 Exercise a,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; }
CNG 140 C Programming36 Exercise a,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; }
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
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); }
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
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
CNG 140 C Programming41 UNION #define AUTO 1 #define BOAT 2 #define PLANE 3 #define SHIP 4
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;
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 */
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); }
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
CNG 140 C Programming46 Common Compiler Errors
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
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