Pointers in C++

Posted on at

              A pointer variable is a variable that stores the address where another object resides. It is
the fundamental mechanism used in many data structures. For instance, to store a list of
items, we could use a contiguous array, but insertion into the middle of the contiguous
array requires relocation of many items. Rather than store the collection in an array, it
is common to store each item in a separate, non contiguous piece of memory, which is
allocated as the program runs. Along with each object is a link to the next object. This
link is a pointer variable, because it stores a memory location of another object. This is the
classic linked list.



To illustrate the operations that apply to pointers, we dynamically
allocate the Int Cell. It must be emphasized that for a simple Int Cell class, there is no
good reason to write the C++ code this way. We do it only to illustrate dynamic memory
allocation in a simple context. Later in the text, we will see more complicated classes,
where this technique is useful and necessary. The new version is shown in Figure.
Line 3 illustrates the declaration of "m".The "*" indicates that "m" is a pointer variable; it is allowed
to point at an Int Cell object. The value of "m" is the address of the object that it points at.

01.  int main( )
02.  {
03.  IntCell *m;
05.  m = new IntCell{ 0 };
06.  m->write( 5 );
07.  cout << "Cell contents: " << m->read( ) << endl;
09.  delete m;
10.  return 0;
11.  }

Program that uses pointers to Int Cell (there is no compelling reason to do

About the author


I'm a student.

Subscribe 281