120 likes | 252 Views
Structures Containing Pointers Lesson xx. Objectives. Review structures Program to demonstrate a structure containing a pointer. Structure Review. c. 2. c.pip. struct card { int pip; char suit; }; int main ( ) { card c; c.pip = 2; c.suit = ‘s’;
E N D
Objectives • Review structures • Program to demonstrate a structure containing a pointer
Structure Review c 2 c.pip struct card { int pip; char suit; }; int main ( ) { card c; c.pip = 2; c.suit = ‘s’; return 0; } ‘s’ c.suit
Structure Containing a Pointer struct xyz { int a; char b; float c; int *ptr; };
Structure Containing Pointers Program #include <iostream> using std::cout; using std::endl; structstructWithPtrs{ int* p1; double* p2; }; int main() { structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; cout << "i1 = " << i1 << " *s.p1 = " << *s.p1 << endl; cout << "f2 = " << f2 << " *s.p2 = " << *s.p2 << endl; return 0; }
Structure Definition structstructWithPtrs{ int* p1; double* p2; };
Variable or Object Declaration structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; (2fe) s s.p1 s.p2
Variable Declarations structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; 100 i1 (1ab) (2fe) s (67b) f2 s.p1 s.p2
Initializing Pointers structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; 100 1ab 67b i1 (1ab) (2fe) s (67b) f2 s.p1 s.p2
Indirection structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; 100 1ab -45.0 67b i1 (1ab) (2fe) s (67b) f2 s.p1 s.p2
Output cout << "i1 = " << i1 << " *s.p1 = " << *s.p1 << endl; cout << "f2 = " << f2 << " *s.p2 = " << *s.p2 << endl; 100 1ab -45.0 67b i1 (1ab) (2fe) s (67b) f2 s.p1 Output i1 = 100 *s.p1 = 100 f2 = -45.0 *s.p2 = -45.0 s.p2
Summary • Review structures • Program to demonstrate a structure • containing a pointer