170 likes | 244 Views
Class 13 Honors. Objectives. Create and use structures Pass structures to functions by value and by reference. i. c. i. c. sample1. sample2. Structures. struct example. { char c; int i; } sample1, sample2;. 25. a. sample2 . c = ‘a’;. sample1 . i = 25;. Structures.
E N D
Objectives • Create and use structures • Pass structures to functions by value and by reference
i c i c sample1 sample2 Structures struct example { char c; int i; } sample1, sample2; 25 a sample2 . c = ‘a’; sample1 . i = 25;
Structures struct card { char face[10]; char suit[10]; } ;int main() { card a, deck[52], *c; face suit Ace Spades strcpy(a.face, “Ace”); a strcpy(a.suit, “Spades”); c = &a; cout << c-> face; cout << (* c) .suit;
face suit face suit face suit deck[0] deck[1] deck[2]... deck struct card deck[52]; strcpy(deck[1] .face, “King”); strcpy(deck[2].face, “Two”); strcpy(deck[0] .suit, “Clubs”); ? Two\0 ? ? Clubs\0 King\0 &deck[0]
Structures struct employee { char last[25]; char first[15]; char mi; float salary; }; place in a .h file programx.h
Passing Structures #include “programx.h” int main ( ) { employee person; input_person (person); } last first mi salary person
last first mi salary person in main last first mi salary emp void input_person( employee emp) { cout <<“enter last name”; cin >> emp.last; } j o n e s \0
last first mi salary j o n e s \0 Person/emp in main void input_person(employee &emp) { cout <<“enter last name”; cin >> emp.last; }
last first mi salary 3E EF Person in main void input_person( employee * emp) { cout <<“enter last name”; cin >> emp->last; } //inside main input_person(&person); 3E EF emp 2
last first mi salary j o n e s \0 3E EF Person in main void input_person( employee * emp) { cout <<“enter last name”; cin >> emp->last; } //inside main input_person(&person); 3E EF emp 2
P. 636 Structures struct GeoInfo { char CityName[25]; char State[15]; long Population; int Distance; }; place in a .h file programx.h
Initialization inside structure NOT allowed; p. 636 struct GeoInfo { char CityName[25] = “Dallas”; char State[15]; long Population; int Distance; };
struct GeoInfo { char CityName[25]; char State[15]; long Population; int Distance; }; GeoInfo location = {“Asheville”, “NC”, 50000, 28}; =15; // not allowed
Declare a variable of type GeoInfo and write interactive code to place data in each field of the structure struct GeoInfo { char CityName[25]; char State[15]; long Population; int Distance; };
struct GeoInfo { char CityName[25]; char State[15]; long Population; int Distance; }; int main() { GeoInfo record; cout << “enter the city name”; cin.getline( record.CityName, 25); …... cout << “enter the Population”; cin >> record.Population;