230 likes | 348 Vues
This document provides a comprehensive overview of structures in C programming, covering their definition, declaration, initialization, and manipulation. Learn about tagged structures, typedefs, and how to create custom types such as enumerated types. Discover how to define structures for various data types, initialize them, and use pointers for accessing fields. By exploring examples like defining a 'student' structure and a 'car' structure with detailed attributes, this guide equips programmers with the knowledge to effectively manage complex data in C.
E N D
EEE 243BApplied Computer Programming Structures §12.3
Review • What is the syntax for defining a type? • The enumerated type is built on which other type? • What is the value of each of the following? enum days {SUN, MON=-2, TUE, WED, THU, FRI, SAT}; • How would I change the above enumerated type to define a new type called DAYS? Prof S.P. Leblanc
Outline • Structures – Definition and Declaration • Tagged • Typedef • Structures - Initialization • Structures –Fields • Structures and pointers • Dynamic memory allocation Prof S.P. Leblanc
Structures • If we only used standard types in our programs, they would be very large, and difficult to maintain. • A structure is a collection of related elements, (called fields), possibly of different types having a single name Prof S.P. Leblanc
1.Structure • If I want to describe my abstraction of a student I could collect the following info: • First name • Last name • College Number • Average • We can create a structure and declare a variable to store this information • This is similar to classes and class members • There are two different ways to declare a structure in C: • Tagged Structure • Type Declaration with typedef Prof S.P. Leblanc
1a. Tagged Structure Definition • Here we show a tagged structure; • struct STUDENT • { • char firstName[15]; • char lastName[25]; • char collegeNumber[6]; • float average; • }; Prof S.P. Leblanc
1a. Tagged Structures Declaration • To declare a variable for this structure, the struct keyword is repeated roughly the same as enum was for enumerated types: struct STUDENT aMilColStudent; Prof S.P. Leblanc
1b. typedef Structures • Similar to enumerated types, typedef may be used to avoid the requirement to repeat the struct keyword with each declaration: • For most applications, you should use type-defined structures, as they are preferable: • typedefstruct • { • char firstName[15]; • char lastName[25]; • char collegeNumber[6]; • float average; • }STUDENT; //name of the type • STUDENT aMilColStudent; //Declare a variable Prof S.P. Leblanc
2. Structure - initialization • Structures are initialised similarly to arrays. If we take the typedefSTUDENT and the variable aMilColStudentfrom the previous slide: STUDENT aMilColStudent = {"Joe", "Shmoe","45239",78.3}; You will have to come back much later to meet this OCdt Prof S.P. Leblanc
Example • Define a typedefstructure for a car, include • the manufacturer, • model name, • transmission type (manual or automatic), • number of doors (2 , 3 , 4 or 5), • colour, (Green, Beige, Grey, Black) • year, • engine size (in # cylinders) • The types from last class can be used in the structure Prof S.P. Leblanc
Example • Using the type just declared, declare a VEHICLE_TYPE variable for Manufacturer Chrysler Model Cordoba Year 1978 Doors 2 Cylinders 8 COLOURBLACK TRANSMISSION MANUAL Prof S.P. Leblanc
Solution (1) typedefenum {MANUAL, AUTOMATIC} TRANSMISSION ; typedefenum { RED, WHITE, YELLOW, GREEN, BEIGE, GREY, BLACK} COLOUR; typedefenum { 2=2, 3, 4, 5} DOORS; Prof S.P. Leblanc
Solution (2) typedefstruct { char manufacturer[25]; char model[25]; intyear; DOORS numDoors; TRANSMISSION transType; COLOUR carColour; intnumCylinders; } CAR; Prof S.P. Leblanc
Solution (3) CAR myFirstCar = { "CHRYSLER", "CORDOBA", 1978, 2, MANUAL, BLACK, 8 }; Prof S.P. Leblanc
3.Structures and fields • Structures are constructed with fields. Everywhere you can use a variable you can use a structure field • Each field can be accessed individually with the structure member operator • (the period) . strcpy(aMilColStudent.firstName, "Bob"); aMilColStudent.collegeNumber = "98876"; You may meet this OCdt some day… Prof S.P. Leblanc
3. Structures Operators, = • Structures are entities that can be treated as a whole, but ONLY during an assignment operation: STUDENT fStudent = {"Jane", "Doe", {'2','3','4','9','8'}, 33.2}; //poor Jane! aMilColStudent = fStudent; • You cannot compare two structures: if (aMilColStudent == fStudent) printf("Totally an error"); Prof S.P. Leblanc
3. Structures and fields • In order to compare structures of the same type, you would need to write a function that compares each field in order: … //function returns 1 if all the field are equal intCompareStudents(STUDENT st1, STUDENT st2) { return ( !strcmp (st1.firstName,st2.firstName) && !strcmp (st1.lastName,st2.lastName) && !strcmp (st1.collegeNumber, st2.collegeNumber) && (fabs(st1.average - st2.average < 0.0001)) ); } Prof S.P. Leblanc
4. Structures and Pointers • Like any other type in C, pointers can point to structures. The pointer points to the first byte of the structure. • You can also use pointers to access fields: STUDENT* pStudent= &aMilColStudent; aMilColStudent.collegeNumber = "12345"; (* pStudent).collegeNumber = "12345"; • Result is the same; but we need the brackets around the dereferencing due to precedence Prof S.P. Leblanc
4. Structures and Pointers • Fortunately C provides another operator that allows us to dereference the pointer and access the field at the same time; the structure selection operator: pStudent->collegeNumber = "54321"; Prof S.P. Leblanc
5. Dynamic memory allocation • Recall that we can allocate memory dynamically • You can also allocate memory for any types including typedef'd structures: typedefstruct { char firstName[15]; char lastName[25]; } NAME; NAME *pName = NULL; pName = (NAME *)malloc (sizeof(NAME)); Prof S.P. Leblanc
Quiz Time • What is printed in the following code? int* pInt; STUDENT aStudent={"Jane", "Doe", "23498", 33.2}; STUDENT* pStudent= &aStudent; pInt= &aStudent.collegeNumber; printf("%s \’s student Number is %ld", (*pStudent).firstName, *pInt); printf("%s \’s student Number is %ld", pStudent->firstName, aStudent.collegeNumber); Prof S.P. Leblanc
Quiz Time • If you declare a variable that is a type-defined structure what operator do you use to access its fields? • If you have a pointer that points to a structure, what operator do you use to access each field? • Can you assign a complete structure to another? • Can you compare structures with == ? Prof S.P. Leblanc
Next lecture • Linked List I Prof S.P. Leblanc