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

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

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

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

Structured Programming Instructor: Prof. K. T. Tsang

Lecture 11: Structure and Union

1

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

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

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

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

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

Declaring a “struct” variable

//declare birthDay as type Date

struct Date birthDay;

birthDay = { 25, 12, 2003};

4

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

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

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

“struct” definition

struct <struct-type>{<type1> <identifier_1>;<type2> <identifier_2>;...

} ;Each identifier

defines a memberin the structure.

It is usually a ‘global’ definition!

6

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

“struct” examplesstruct 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 structuretypes as members.

The “StudentRecord” structure has 5 members.

7

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

Declaring & initializing

StudentRecord student1;

student1 = { “John Li”,

20100456, 2010,

“Statistics”,

‘M’, {24,6,1990} }

8

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

“struct” declaration

• Declaration of a variable of struct type:

<struct-type> <identifier_list>;

• Example:StudentRecord Student1, Student2;

Student1 and Student2 are variables of StudentRecord type.

9

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

Member access (dot operator)The members of a struct type variable are accessed

with the dot (.) operator:

<struct-variable>.<member_name>;

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

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

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

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

Examplestruct 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

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

Output from previous example

Input book informationWar_and_Pease LeonTolstoy ClassicBooks1200 23.90

Output :War_and_PeaseLeonTolstoyClassicBooks120023.9 13

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

Example of Nested structuresstruct 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

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

Arrays of structures

• An ordinary array: One type of dataint 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

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

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

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

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

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

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

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

Pointer to “struct”• Declaration of pointer to struct<struct-type> *<identifier_list>;

• 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

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

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

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

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

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

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

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

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

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

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 dataint i;float f;main(){

data.f_value = 5.0; //okdata.i_value = 1; //f_value overwritteni = data.i_value; //okf = data.f_value; //errordata.f_value = 6.3 //data.i_value

losti = data.i_value //error

} 24

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

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

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

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

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

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

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

Using sizeof operator toThe 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

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

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