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:
Stuff theOne; Stuff* ptr; ptr = &theOne;
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:
struct Date { short theMonth, theDay, theYear; }; Date theDate; Date* ptr = &theDate;
then the instance theDate using the dot operator could be initialized as follows:
theDate.theMonth = 7; theDate.theDay = 4; theDate.theYear = 1776;
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:
ptr -> theMonth = 7; ptr -> theDay = 4; ptr -> theYear = 1776;
In addition, these last three statements are the same as following statements:
(*ptr).theMonth = 7; (*ptr).theDay = 4; (*ptr).theYear = 1776;
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:
ptr1 = new Date;
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:
ptr1 -> theMonth = 1; ptr1 -> theDay = 1; ptr1 -> theYear = 2004;
as in the example PTRSTRC.CPP.
Warning: Don't forget to delete/deallocate any memory created by the new operator.