cs 192 lecture 17-18 winter 2003 january 26-27, 2004 january 28-29, 2004 dr. shafay shamail

22
CS 192 Lecture 17-18 Winter 2003 January 26-27, 2004 January 28-29, 2004 Dr. Shafay Shamail

Post on 19-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

CS 192

Lecture 17-18

Winter 2003

January 26-27, 2004

January 28-29, 2004

Dr. Shafay Shamail

Structures

• Suppose you want to store data about your favorite person

• Are all the interesting attributes of him/her of the same data type?

• What if you use arrays? How many needed?• Structure is a compound data type• Compound = Fancy word for: can have various data

types stored in it• A single structure needed to store your favorite person• If you have a bunch of favorites, you just need what?• An array of structures

Structure

• A collection of items of same or different type(s) in contiguous memory

Structuresstruct Favorite {

char name[40]; char address[70];int weight;double height;

};//don’t forget semicolon as it is a statement

• Favorite is structure name (also called tag)• height, name etc. are its members• Now we can declare variables of this datatype:

favorite person1, person2;

• Could also have donestruct favorite{…}person1, person2;//multiple variables

struct{…}person; //can’t declare new variables ahead

Structuretypedef struct TagName

{ // data members

char name[40];

char address[70];

int weight; double height;

}TypeName;

typedef struct Favorite

{

char name[40];

char address[70];

int weight; double height;

}Favorite;

Initialization of Membersstruct Favorite{

char name[40]; char address[70];char *phone;int weight; double height;

} person;

strcpy(person.name, "Ali");gets(person.address);person.phone = new char [strlen(“555-1122”)+1];strcpy(person.phone,"555-1122“);person.weight = 160;person.height = 6.0;

• Members of a structure accessed thru dot operator• cout<<person.name<<endl<<person.height<<endl;

Initialization of Members

struct Favorite

{

char name[40];

char address[100];

int weight;

double height;

};

Favorite person = {"Sherlock", "221 Baker Street", 150, 6.2};

• What if we do:Favorite person = {"Sherlock"};

cout<<person.name<<person.address<<person.weight<< person.height<<endl;

• The rest automatically initialized to zero or null

An Example#include <iostream.h>#include <cstring>typedef struct Favorite{

char name[40];char address[100];int weight;double height;

} Favorite;int main(){

Favorite person;strcpy(person.name, "Ali");strcpy(person.address,"LUMS, Pakistan“);person.weight = 160;person.height = 6.0;cout<<person.name<<endl<<person.address<<endl<<person.weight<<

endl<<person.height;return 0;

}

• Note placement of structure (global). Can also be placed inside main(). Better here if other functions use it

Arrays of Structures typedef struct Item { char name[40]; // name of item double cost; // cost double retail; // retail price int on_hand; // amount on hand int lead_time; // number of days before resupply } Item; Item invtry[10];

• Now invtry is an array of 10 structures, each having all the data items of item

• cin>>invtry[0].name; //OR gets(invtry[0].name);cin>>invtry[0].cost;

• cout<<invtry[0].name;cout<<invtry[0].cost;

• cout<<invtry[0].name[2]; //gives 3rd character of name

Functions Passing and Returning Structures• Passed by value. Original unaffected. Overhead if large structure #include <iostream.h> typedef struct TravelTime { int hours; int mins; } TravelTime;

TravelTime sum(TravelTime t1, TravelTime t2); void main() {

TravelTime day1 = {5, 45};//5 hrs, 45 mins TravelTime day2 = {4, 55};//4 hrs, 55 mins TravelTime trip = sum(day1, day2); cout<<"Two-day total: "<<trip.hours<<" hours, " <<trip.mins<<" minutes\n"; } TravelTime sum(TravelTime t1, TravelTime t2) {

TravelTime total; total.mins = (t1.mins + t2.mins) % 60; total.hours = t1.hours + t2.hours + (t1.mins + t2.mins)/60; return total; }

Output: Two-day total: 10 hours, 40 minutes• How to pass an array by value?

Assigning Structures• Can assign one structure to another of the same type• Memberwise Assignment takes place, even if array #include <iostream.h> struct SType { int a, b; }; int main() { SType svar1, svar2; svar1.a = svar1.b = 10; svar2.a = svar2.b = 20; cout << svar1.a << ' ' << svar1.b<<endl; cout << svar2.a << ' ' << svar2.b<<endl; svar2 = svar1; // assign structures cout << svar1.a << ' ' << svar1.b<<endl; cout << svar2.a << ' ' << svar2.b<<endl; return 0; }Output: 10 10 20 20 10 10 10 10

Assigning Structures

struct SType1 { int a, b; }; struct SType2 { int a, b; };

SType1 svar1; SType2 svar2; svar2 = svar1; // Error - type mismatch

• Even though both svar1 and svar2 are physically the same, they are not variables of the same structure

Pointers to Structures• Can declare a pointer to a struct just as we do for others

typedef struct SType1 { int a, b; }SType;

SType svar1;SType1 *ptr; //ptr is a pointer to struct stype

• We can now access members with another operator too, if we use the pointerptr = &svar1;ptr->a = 1; //Arrow operatorptr->b = 2;cout<<ptr->a;cout<<ptr->b;cout<<svar1.a;cout<<svar1.b;

What does *ptr give us? Takes us to the structure. Hence, ptr->a is equivalent to (*ptr).a

Pointers to Structures #include <iostream.h> typedef struct Inflatable { char name[20]; float volume; double price; } Inflatable; int main() { Inflatable dinghy; Inflatable *ps = &dinghy; cin>>ps->name; cin>>(*ps).volume; cin>>ps->price; cout<<(*ps).name<<endl; cout<<ps->volume<<endl; cout<<dinghy.price<<endl; return 0; }

Functions Receiving and Returning Pointers to Structures

• To implement call-by-reference #include <iostream.h> typedef struct TravelTime { int hours; int mins; }; TravelTime * sum(travel_time *t1, travel_time *t2); void main() { TravelTime day1 = {5, 45};//5 hrs, 45 mins TravelTime day2 = {4, 55};//4 hrs, 55 mins TravelTime *trip = sum(&day1, &day2); cout<<"Two-day total: "<<trip->hours<<" hours, " <<trip->mins<<" minutes\n"; } TravelTime * sum(TravelTime *t1, TravelTime *t2) {

TravelTime total; total.mins = (t1->mins + t2->mins) % 60; total.hours = t1->hours + t2->hours + (t1->mins + t2->mins)/60; return &total; }

Functions Receiving and Returning References to Structures

#include <iostream.h> typedef struct MyStruct { int a; int b; }; MyStruct & f(MyStruct &var); int main() {

MyStruct x, y; x.a = 10; x.b = 20; cout << "Original x.a and x.b: "; cout << x.a << ' ' << x.b << '\n';//10, 20 y = f(x);//assigning one struct to the other cout << "Modified x.a and x.b: "; cout << x.a << ' ' << x.b << '\n';//100, 1 cout << "Modified y.a and y.b: "; cout << y.a << ' ' << y.b << '\n';//100, 1 return 0; }

MyStruct & f(MyStruct &var) { var.a = var.a * var.a; var.b = var.b / var.b; return var; }

Dynamic Structures

• Allocated memory at run time• Format same as always#include <iostream.h>#include <cstdio> typedef struct Inflatable { char name[20]; float volume; double price; } Inflatable;

void main() {

Inflatable *p = new Inflatable; gets(p->name);

cin >> p->volume;cin >> p->price;

}

Dynamic Structures#include <iostream.h> typedef struct Simple { int ival; double dval; } Simple;

void func(Simple* s);

int main(void) { Simple* s1=new Simple; s1->ival=10; (*s1).dval=1.5; //can we do *s1.dval = 1.5; ? func(s1); cout << s1->ival << " , "<< s1->dval << endl;

delete s1; return 0; } void func(Simple* s) { s->ival++; s->dval++; }

Arrays and Pointers within Structures• A struct member can be of any valid data typestruct AStructure{ int nums[10][10]; // 10 x 10 array of ints float b;} var;

• To access nums[3][7], do var.nums[3][7]• A struct can have a pointer to itself as its member

struct Recursive{ int a; float b; Recursive *p;} var;

• A very useful device. Commonly used in linked data structures

Structures within Structures (nested structs)typedef struct Addr { char name[40]; char street[40]; char city[40]; int postcode;}Addr;typedef struct Emp {

Addr address;//address has datatype struct addr float wage;} Emp;Emp worker;

• How to access postcode member of structure variable workerworker.address.postcode = 54700;

• What if addr *address;– worker.address->postcode = 54700;– We can then also do worker.address = new addr;

• Can end up with student.quarter.course.grade

Structures within Structures #include <iostream.h> typedef struct Distance { int feet; float inches; } Distance;

typedef struct Room{ Distance length; Distance width; } Room;

int main() { Room dining; cin>>dining.length.feet; cin>>dining.length.inches; cin>>dining.width.feet; cin>>dining.width.inches; float l=dining.length.feet+dining.length.inches/12; float w=dining.width.feet+dining.width.inches/12; cout<<"Dining room area is "<<l*w<<" square feet\n"; return 0; }

• Could have initialized as: Room dining = {{13, 6.5},{10,0.0}};

Comparing Structures

• Illegal to compare even two variables of same struct data type?• Might be holes inside memory • Word: Standard memory unit used to store data. System

dependant. Usually 2 or 4 bytes• System stores bits left-to-right or right-to-left in a word

struct holes { char c; int i; }var1, var2; var1.c=var2.c='a'; var1.i=var2.i=8; cout<<(var1==var2);/**Error**/ }

• Holes for var1 and var2 will probably have different junk values. Write your own functions to compare field by field

• Holes make sizeof(some_struct) give larger value

01100001 0000100000000000

word word

holeByte 0 1 2 3