review structures program to demonstrate a structure containing a pointer

12
Structures Containing Pointers Lesson xx

Upload: willis-mills

Post on 29-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

Structures Containing PointersLesson xx

In the last module, we discussed pointer to structures. In this presentation we want to talk about structures that contain pointers.

1ObjectivesReview structuresProgram to demonstrate a structure containing a pointer

Our goal is to review structures and then segue into structures that contain pointers.2Structure Reviewstruct card { int pip; char suit; };

int main ( ) { card c; c.pip = 2; c.suit = s; return 0; }2sc.pipc.suitc

At the beginning of our code, we set up a structure definition. We have defined a structure called card which contains two data members called pip and suit. In main( ), we set up a card variable or sometimes we call it a card object with the statement: card c; Object c, is composed of 2 parts, c.pip and c.suit. Think of it this way, object c represents the playing card that is the 2 of spades.3Structure Containing a Pointerstruct xyz { int a; char b; float c; int *ptr; };

In our previous structures, the data members were basic data types like int, char, and float. Not only can basic data types be members of a structure but, so can pointers. In our example shown here, the structure xyz, contains 3 data member that are basic data types. The 4th data member is called ptr and is a pointer to an int. This is an example a structure that contains a pointer. Lets look at a program that shows you how to manipulate structures that contain pointers.4Structure Containing Pointers Program #include using std::cout; using std::endl;

struct structWithPtrs { int* p1; double* p2; }; int main() { structWithPtrs s; int i1 = 100; double f2; s.p1 = &i1; s.p2 = &f2; *s.p2 = -45.0; cout