Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1.

Similar presentations


Presentation on theme: "Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1."— Presentation transcript:

1 Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1

2 Motivation An array is a collection of variables of same type (e.g. int, char, float …) A collection of variables of different types is a ‘structure’ Structures hold data that belong together. Examples: –Student record student id, name, major, gender, start year, … –Bank account: account number, name, currency, balance, … –Address book: name, address, telephone number, … In database applications, structures are called records. 2

3 Example structure: “ Date ” A “Date” type: –Day (integer) –Month (integer) –Year (integer) Example: struct Date { int day; int month; int year; } ; The new composite type “Date” structure has 3 members. 3

4 Declaring a “struct” variable // declare birthDay as type Date struct Date birthDay; birthDay = { 25, 12, 2003}; 4

5 Accessing members in the structure // another way to declare new variable of type ‘Date’ Date christmas; christmas. day = 25; christmas. month = 12; christmas. year = 2006 Access to member variables using dot operator 5

6 “ struct ” definition struct { ;... } ; Each identifier defines a member in the structure. It is usually a ‘global’ definition! 6

7 “ struct ” examples struct BankAccount{ char Name[]; int AcountNo[10]; double balance; Date Birthday; }; struct StudentRecord{ char Name[]; int Id; int graduatingYear; char Dept[66]; char gender; Date Birthday; }; The “BankAcount” structure has simple, array and structure types as members. The “StudentRecord” structure has 5 members. 7

8 Declaring & initializing StudentRecord student1; student1 = { “John Li”, 20100456, 2010, “Statistics”, ‘M’, {24,6,1990} } 8

9 “ struct ” declaration Declaration of a variable of struct type: ; Example: StudentRecord Student1, Student2; Student1 and Student2 are variables of StudentRecord type. 9

10 Member access (dot operator) The members of a struct type variable are accessed with the dot (. ) operator:. ; StudentRecord Student1; Student1.Name = “Wang Jing"; Student1.Id = 12345; Student1.Dept = “Statistics"; Student1.gender = 'M'; printf("The student is ”); if (Student1.gender == ‘F’)printf("Ms. “); else printf("Mr. “); printf(“%s\n”, Student1.Name); 10

11 struct-to-struct assignment The value of one struct type variable can be assigned to another variable of the same struct type. Example: Student1.Name = "Chen Ming"; Student1.Id = 12344; Student1.Dept = "COMP_SC"; Student1.gender = 'M'; Student2 = Student1; 11

12 Example struct book_info { char title[90]; char author[50]; char publisher[80]; int pages; float price; } main() { struct book_info novel1, math101; printf (“Input book information\n”); scanf (“%s %s %s %d %f”, novel1.title, noel1.author, novel1.publisher, &novel1.pages, &novel1.price); printf (“%s\n%s\n%s\n%d %f\n”, novel1.title, noel1.author, novel1.publisher, novel1.pages, novel1.price); } 12

13 Output from previous example Input book information War_and_Pease LeonTolstoy ClassicBooks 1200 23.90 Output : War_and_Pease LeonTolstoy ClassicBooks 1200 23.9 13

14 Example of Nested structures struct Point{ double x, y; }; struct Line{ Point p1, p2; }; struct Triangle{ Point p1, p2, p3; }; Point P; Line L; Triangle T; (P.x, P.y) (L.p1.x, L.p1.y) (L.p2.x, L.p2.y) (T.p2.x, T.p2.y) (T.p1.x, T.p1.y) (T.p3.x, T.p3.y) 14

15 Arrays of structures An ordinary array: One type of data int ia[10]; An array of structs: a package of data in each array element. Point points[12]; points[0].x = 3.45; points[0].y = -2.89; points[1] = { 24.1, 7.4}; 15

16 Arrays of structures: exmple StudentRecord CSclass[100]; CSclass[98].Name = “Wan Jing"; CSclass[98].Id = 100345; CSclass[98].graduatingYear = 2009; CSclass[98].Dept = "COMP_SC"; CSclass[98].gender = 'M'; CSclass[0] = CSclass[98]; 16

17 Arrays inside a “struct” We can use array of “struct” inside a “struct”. Example: struct rectangle{ Point vertex[4]; }; rectangle sq; Assign values to Sq sq.vertex[0].x = 4; sq.vertex[0].y = 3; sq.vertex[1] = { 9, -2}; 17

18 Exercise on “struct” Using the definitions of structures given in our Lectures: struct Point { double x, y; }; struct rectangle { Point vertex[4]; }; Write a function to return the 4 vertexes of a rectangle when given 3 of the vertexes, with the following prototype: rectangle complete_rectan (Point v1, Point v2, Point v3); 18

19 Pointer to “ struct ” Declaration of pointer to struct * ; Example: StudentRecord Student1; StudentRecord *pStudent2; Student1.Name = "Bill Gates"; Student1.Id = 666; Student1.Dept = “Math"; Student1.gender = 'M'; pStudent2 = &Student1; (*pStudent2).Id = 444; pStudent2->Id = 555; pStudent2->gender = ‘F'; Dot operator for ‘object’  for ‘pointer’ 19

20 Summary on “struct” “struct” is a complex data type defined by user/programmer. It is a collection of variables of different types packed together. Members inside the “struct” can be initialized/accessed using the dot operator. Variables and pointers can be declared for the “struct” defined by programmer. 20

21 Union declaration A “union” is similar to a “struct”; however it defines a single storage location that can be given many different member name: union value { int i_value;//integer version of value float f_value;//float version of value } Both i_value & f_value share the same memory. 21

22 Memory storage for a “struct” struct svalue { char c; int m; float f; } At any point in time, all the members in the struct may have a value. Memory allocation for svalue C (1 byte) m (4 bytes)f (8 bytes) 22

23 Memory storage for a “union” union uvalue { char c; int m; float f; } C (1 byte) m (4 bytes) f (8 bytes) At any point in time, only one of the members in the union may have a value. Memory allocation for uvalue 23

24 Example union value {// declare a union type value int i_value; //member in union that shares float f_value; //same memory block } data;// declare a variable data int i; float f; main() { data.f_value = 5.0;//ok data.i_value = 1; //f_value overwritten i = data.i_value;//ok f = data.f_value;//error data.f_value = 6.3//data.i_value lost i = data.i_value//error } 24

25 Remember As a general rule, do not place the struct/union name after the closing brace in the definition. That will be treated as a struct/union variable. The struct/union name must be placed before the opening brace but after the keyword “struct/union”. 25

26 Union characteristics At any point in time, only one of the members in the union may have a value. When a value is assigned to one member, all other members of the union become undefined. The amount of storage allocated for a union is at least as much as the amount to contain its largest data member. No union member can be a reference. 26

27 sizeof operator: returns the number of bytes its argument occupies int a = 3; char s = ‘z’; double d = 1.03; int *pa = &a; char *ps = &s; double *pd = &d; cout << sizeof(pa) << sizeof(*pa) << sizeof(&pa) << sizeof(a) << endl; cout << sizeof(ps) << sizeof(*ps) << sizeof(&ps) << sizeof(s) << endl; cout << sizeof(pd) << sizeof(*pd) << sizeof(&pd) << sizeof(d) << endl; 27

28 Using sizeof operator to The actual size of a “struct” or “union” variable may be difficult to account for and may change from machine to machine. The sizeof operator is helpful to determine the size of a variable of any structure or type. The expression “ sizeof (struct x) ” will return the number of bytes to hold the structure x. The expression “ sizeof (y) ” will return the number of bytes to hold the variable y of any structure. If y is an array of x, then sizeof(y)/sizeof(x) is the dimension of the array y. 28

29 Summary on “union” “union” is a single storage location shared by many different members with different name. When a value is assigned to one member, all other members of the union become undefined. The sizeof operator is useful to determine the size of a variable of any structure/union or basic types. 29


Download ppt "Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1."

Similar presentations


Ads by Google