cosc237/structures1 structures aggregate data types record - single variable name for the whole...
TRANSCRIPT
cosc237/structures 1
Structures
• aggregate data types
• record - single variable name for the whole collection
• composed of several variables - fields,BUT, unlike arrays, members also have names -field names, and may be different types;
• member
cosc237/structures 2
Declaration
1. define template - form of the structure;struct name (or tag){ type member1; type member2; … }; // no space reserved2. Declare structure variablestructname varname; /* allocates space */
cosc237/structures 3
Example:
struct Employee // structure tag{ int idNumber; char name[30]; float salary;};• essentially creates a new variable typeEmployee emp1;Employee newEmp;
cosc237/structures 4
Struct cont’d
• size determined by sum of all individual members• ; required ,tag is optional - anonymous
struct
{
int idNumber;
char name[30];
float salary;
} newEmp;
cosc237/structures 5
struct AnimalType // declares a struct data type, does not allocate memory
{ // struct members long id; char name[20]; char genus[10]; char species[10]; char country[15]; int age; float weight;
}; // declare variables of AnimalType AnimalType animal1; AnimalType animal2;
cosc237/structures 6
templates
struct point { int x; //x-coordinate int y; //y-coordinate }; { int idNumber; char LName[30]; char FName[15]; float salary; };
cosc237/structures 7
Scope of member name• Member name is local to structstruct Employee // structure tag{ int idNumber; char name[30]; float salary;};struct Student{ char ssNum[9]; char name[30];}
cosc237/structures 8
Declaration for structure variables:
• allocates space
• Example: 1. point point1; 2. Employee emp1; Employee emp2;
cosc237/structures 9
Accessing individual members
• dot (.) operator is the member selection operator.• structureName.memberName• memberName not unique• it is possible for members of different struct types to have
the same identifiers. Also a non-struct variable may have the same identifier as a structure member.
• Examples: thisAnimal.weight, point1.x, point1.y, point2.x, point2.y; emp1.idNumber = 111; emp2.salary = 42000;
cosc237/structures 10
Initialization
• structure variables can be initialized when they are declared:
Employee newEmp = {999, "Ford", "John", 50000};
point point1 = {5, 10}; //x = 5 y = 10
cosc237/structures 11
Reference
animal1.age = 18; animal1.age++;animal2.id = 2037581; cin >> animal1.weight; animal2.name = "giant panda";animal2.genus[0] = toupper(animal2.genus[0]);newEmp.salary = newEmp.salary + 10000;
• sizeof newEmp or sizeof (Employee)
cosc237/structures 12
Strings in structures
• newEmp.name - “George”
• newEmp.name[0] - ‘G’
• newEmp.name[1] - ‘e’
cosc237/structures 13
Assignment
• one struct variable can be assigned to another, if both variables are of the same type– Employee emp1,emp2;– emp1 = emp2;
• Type compatibility - only if their types are identical or are renamings of the same type
• typedef Employee Worker;
cosc237/structures 14
Operations valid on an entire struct type variable:
• Assignment operation: one struct variable can be assigned to another struct variable if both variables are of the same type.
• Example: – Employee emp1, emp2;
emp1 = emp2; //copies the entire structure, member by member
cosc237/structures 15
Telling Functions about Structures
• Structures can be passed as function arguments and can be returned as function return values.
• It's wasteful to pass large structures to a function that uses only one or two members of the structure.
• Can be passed by value or ref using same method as int, float, etc.
cosc237/structures 16
Invalid Structure Operations(i.e.structure as a whole unit)
• I/O: cannot print or input structures as a whole• cout >> newEmp; // invalid• cout >> emp1.idNumber;
• Comparison: cannot compare entire structures• if (emp1 < emp2) // invalid
if (emp1.idNumber < emp2.idNumber)… // valid
• Arithmetic: cannot do arithmetic on entire structures • newEmp = emp1 + emp2; // invalid• newEmp.salary = emp1.salary + emp2.salary;// valid
cosc237/structures 17
Examples of valid operations• animal1 = animal2; // assignment, same type
WriteOut(animal2); // value parameter ChangeAge(animal2); // reference parameter animal1 = GetAnimalData( ); // return value of function
• void ChangeAge ( AnimalType& thisAnimal) // struct as function argument { thisAnimal.age++; }
• AnimalType GetAnimalData ( ) // struct returned as function return value // Obtains all information about an animal from keyboard { AnimalType thisAnimal; char response; do { // have user enter all members until they are correct . . . } while (response != 'Y' ); return thisAnimal; }
cosc237/structures 18
Hierarchical or nested structures struct DateType {
int month; // Assume 1 . . 12 int day; // Assume 1 . . 31 int year; // Assume 1900 . . 2050
}; struct StatisticsType {
float failRate; DateType lastServiced; // DateType is a struct type int downDays;
}; struct MachineRec {
int idNumber; char description[30]; StatisticsType history; // StatisticsType is a struct type DateType purchaseDate; // DateType is a struct type float cost;
}; MachineRec machine; //variable of type MachineRec cout << machine.history.lastServiced.year; // may be 2001
cosc237/structures 19
Examplestruct point {
int x; //x-coordinate int y; //y-coordinate
}; struct line {
point start; // start point point end; // end point
}; line diagonal; // variable of type line cout << diagonal.start.x; //the x-coord of the start point
cosc237/structures 20
• In general, structs are worthwhile only when used in combination with arrays (and, in later chapters, with pointers). Arrays and structs may be combined in various ways to form complex data structures. We can have arrays of structs, structs that contain arrays, arrays of structs with array components, and so on.
cosc237/structures 21
Array of Structures
• Declarationconst int NUM_COMP_EMP = 20;Employee compDept[NUM_COMP_EMP];
• reference:• arrayName[index].someMember
compDept[0].namecompDept[1].idNnumber
• not compDept.salary[0]• compDept[2].name[3]
cosc237/structures 22
Example
struct point
{ int x; //x-coordinate int y; //y-coordinate
};
point points[10]; //array variable of type point
cosc237/structures 23
Example
/* print the names of the employees in the computer department */
for (i = 0; i < NUM_COMP_EMP; i++)
cout << compDept[i].name << endl;
cosc237/structures 24
Unions
• device that lets you store different data types in the same memory space
• when several variables of different names refer to the same storage space;
• compiler reserves memory large enough to hold the largest data type
cosc237/structures 25
Declaration: (similar to structures)
union MixedArray{ char name[10]; int age; float salary; double census; };• Define union variables:MixedArray p0;MixedArray save[10];
cosc237/structures 26
Exa.
union Holdem{ int digit; double bigfl; char letter;} fit;fit - sizeof doublefit.digit = 23;/* 23 is stored in fit,4 bytes used */fit.bigfl = 2.0;/* 23 cleared, 2.0 stored; 8 bytes usedfit.letter = 'h'; /* 2.0 cleared, h stored, 1 byte used */
cosc237/structures 27
Anonymous Unions
union { int someInt; float someFloat;};• member names are not local to union• dot notation not used• someInt = 67;• used with Variant Records
cosc237/structures 28
Variant Records
• Struct consisting of type field and one or more anonymous unions
• the member the anonymous union is called variant
• avoid nesting variant records within variant records
• always use a type field