More about Pointers

Advanced uses of pointers. These include pointers to pointers, functions with a variable number of arguments, and pointers to functions.
An application that defines a class used to represent dynamic matrices is introduced.

Pointer To Pointers

The function accSort()

// accSort.cpp: Sorts an array of pointers to accounts
//              according to the account numbers
// ---------------------------------------------------
   
#include "account.h"
   
void ptrSwap(Account**, Account** );
   
void accSort( Account** kptr, int n)
{
   Account **temp, **minp, **lastp;
   lastp = kptr + n - 1;    // Pointer to the last
                            // pointer in the array.
   
   for(  ; kptr < lastp; ++kptr )
   {
     minp = kptr;
   
     for( temp = kptr + 1; temp <= lastp; ++temp )
     {
       if( (*temp)->getNr() < (*minp)->getNr() )
           minp = temp;
     }
     ptrSwap( kptr, minp );
   }
}
   
void ptrSwap( Account **p1, Account **p2 )
{
   Account *help;
   help = *p1; *p1 = *p2; *p2 = help;
}

Motivation

Pointer variables are objects that have an address in memory, and this means you can use pointers to address them. It is thus possible to create pointers to pointers. This is necessary if
  • an array of pointers is to be dynamically allocated, or
  • a function expects an array of pointers as an argument.
In both cases you need to declare a pointer variable that can access the first element in the array. Since each element in the array is a pointer, this pointer variable must be a pointer to a pointer.

Generating Pointer Arrays Dynamically

Now let's look into creating a dynamic array of pointers to Account class objects.
Example:
Account** ptr = new Account*[400]; 
The pointer ptr is now pointing at the first pointer in the array with a total of 400 Account* type pointers. The array elements can be addressed as follows:
*ptr
and
ptr[0]
(pointer to index 0)
*(ptr + i)
and
ptr[i]
(pointer to index i)
Access to objects managed by the array is achieved as follows:
**ptr
and
*ptr[0]
(object addressed by pointer at index 0)
**(ptr+i)
and
*ptr[i]
(object addressed by pointer at index i)

Pointer Arrays as Arguments

When you define a function that expects an array of pointers as an argument, you must define parameters to match.
Example:
void accSort( Account **kptr, int len); 
You can use the kptr parameter to manipulate a pointer array whose length is stored in the second parameter, len. After calling
Example:
accSort( ptr, 100); 
kptr points to the first pointer ptr[0] in the pointer array ptr. Instead of Account **kptr you can also use the equivalent form Account *kptr[].
The opposite page shows an implementation of the function accSort(). The function uses the selection sort algorithm (which you have already worked with) for sorting. In this case it is important not to sort the accounts itself, but to sort the pointers instead. This saves time-consuming copying.

Post a Comment

0 Comments