The sections of this chapter introduced the concept of pointers and all the operators needed to work with them and dynamic memory. Pointers and their operators are a recurring theme we encounter throughout most of the remaining chapters of the text. But, it is often easier to understand abstract concepts like pointers with a concrete use. So, before we end the chapter, let's look at two detailed, albeit simplified, examples to help solidify the pointer concept and syntax.
Programmers use pointers and dynamic memory allocation to create dynamic or linked data structures. The names describe a data structure constructed with dynamic memory allocated on the heap and linked with pointers, making both appropriate. Figures 1 and 2 illustrate two examples of these structures: linked lists and binary trees. Programmers call the large boxes in the examples nodes, and the arrows represent pointers called links. C++ programs implement nodes as objects instantiated from structures (the next chapter) or classes. Nodes contain the data we wish to store in the structure and one or more pointers linking them together. The "data" may span a broad spectrum of complexity - anything from a single data element like a character to thousands of complex data elements.
Programmers can implement dynamic data structures and their nodes in many ways. For example, a node can embed the data or have a pointer to a separate structure containing the data. Lists can be sorted (e.g., alphabetically) or unsorted. The link in the last list node may be nullptr or point to the first node in the list. A list may have links pointing in one direction or two. Binary trees can be balanced (keeping the left and right sides about the same height) or unbalanced. Sometimes, binary trees are back-threaded with pointers from the nodes back up the tree. When using dynamic structures, programmers always match the structure's behaviors with the problem they are solving.
Embedded Data
Pointer To Data
Two node options. By "handcrafting" nodes for specific problems, programmers can embed data in the node or save a pointer to it. They can generalize the data structures (enable them to manage any data) by separating the organizing and data operations. Programmers can generalize the pointer version by making the link a void pointer: void*. The text elaborates void pointers in a subsequent chapter. Templates, detailed in Chapter 13, offer a more elegant solution.
We conclude with a few simplified code fragments implementing a linked list append operation. The code illustrates some of the pointer operators introduced in the chapter. The code is a brief introduction and may seem mysterious now, but it will become understandable as you continue your studies. The following statements assume the program has a class named node that has:
A data field represented as a single variable: char data;.
A link field, implemented as a pointer to a node: node* link;.