Pointers to Structures


In a previous lecture, pointers to system data types were studied. It is not only possible to have pointers to system data types, but it is also possible to have pointers to structures as well. For example, suppose that Stuff is a structure, theOne is an instance of Stuff, then ptr can be defined as a pointer to Stuff and it can be made a pointer to the instance: theOne in the following manner:

image from book

 Stuff theOne; Stuff* ptr; ptr = &theOne; 

image from book

This looks very much like the examples in a previous lecture where system data types were used. What is different is that this pointer may be used to manipulate the members of the instances. For example suppose that the structure Date, the instance theDate and the pointer ptr to Date are defined as follows:

image from book

 struct Date { short theMonth,         theDay,         theYear; }; Date theDate; Date* ptr = &theDate; 

image from book

then the instance theDate using the dot operator could be initialized as follows:

image from book

 theDate.theMonth = 7; theDate.theDay = 4; theDate.theYear = 1776; 

image from book

However, since the pointer ptr knows where theDate is, it may be used to assist in the initialization of the data members as well. This can be done using the dereference operator -> (also called the member access operator or the arrow operator). For example the statements above could be rewritten as follows:

image from book

 ptr -> theMonth = 7; ptr -> theDay = 4; ptr -> theYear = 1776; 

image from book

In addition, these last three statements are the same as following statements:

image from book

 (*ptr).theMonth = 7; (*ptr).theDay = 4; (*ptr).theYear = 1776; 

image from book

since *ptr is in this case another name for theDate.

The most interesting use of these pointers is when the new operator is used to create unnamed memory dynamically as in the following:

image from book

 ptr1 = new Date; 

image from book

In this case, there is no named instance that could be used to access the members as above. However using the member access operator and the pointer ptr1, the members of this unnamed memory may be initialized as in the following:

image from book

 ptr1 -> theMonth = 1; ptr1 -> theDay = 1; ptr1 -> theYear = 2004; 

image from book

as in the example PTRSTRC.CPP.

 Warning:  Don't forget to delete/deallocate any memory created by the new operator.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net