Previous Page
Next Page

9.4. Pointers to Arrays and Arrays of Pointers

Pointers occur in many C programs as references to arrays , and also as elements of arrays. A pointer to an array type is called an array pointer for short, and an array whose elements are pointers is called a pointer array.

9.4.1. Array Pointers

For the sake of example, the following description deals with an array of int. The same principles apply for any other array type, including multidimensional arrays.

To declare a pointer to an array type, you must use parentheses, as the following example illustrates:

int (* arrPtr)[10] = NULL; // A pointer to an array of
                           // ten elements with type int.

Without the parentheses, the declaration int * arrPtr[10]; would define arrPtr as an array of 10 pointers to int. Arrays of pointers are described in the next section.

In the example, the pointer to an array of 10 int elements is initialized with NULL. However, if we assign it the address of an appropriate array, then the expression *arrPtr yields the array, and (*arrPtr)[i] yields the array element with the index i. According to the rules for the subscript operator, the expression (*arrPtr)[i] is equivalent to *((*arrPtr)+i) (see "Memory Addressing Operators" in Chapter 5). Hence **arrPtr yields the first element of the array, with the index 0.

In order to demonstrate a few operations with the array pointer arrPtr, the following example uses it to address some elements of a two-dimensional arraythat is, some rows of a matrix (see "Matrices" in Chapter 8):

int matrix[3][10];       // Array of three rows, each with 10 columns.
                         // The array name is a pointer to the first
                         // element; i.e., the first row.
arrPtr = matrix;         // Let arrPtr point to the first row of
                         // the matrix.
(*arrPtr)[0] = 5;        // Assign the value 5 to the first element of the
                         // first row.
                         //
arrPtr[2][9] = 6;        // Assign the value 6 to the last element of the
                         // last row.
                         //
++arrPtr;                // Advance the pointer to the next row.
(*arrPtr)[0] = 7;        // Assign the value 7 to the first element of the
                         // second row.

After the initial assignment, arrPtr points to the first row of the matrix, just as the array name matrix does. At this point you can use arrPtr in the same way as matrix to access the elements. For example, the assignment (*arrPtr)[0] = 5 is equivalent to arrPtr[0][0] = 5 or matrix[0][0] = 5.

However, unlike the array name matrix, the pointer name arrPtr does not represent a constant address, as the operation ++arrPtr shows. The increment operation increases the address stored in an array pointer by the size of one arrayin this case, one row of the matrix, or ten times the number of bytes in an int element.

If you want to pass a multidimensional array to a function, you must declare the corresponding function parameter as a pointer to an array type. For a full description and an example of this use of pointers, see "Arrays as Function Arguments" in Chapter 8.

One more word of caution: if a is an array of ten int elements, then you cannot make the pointer from the previous example, arrPtr, point to the array a by this assignment:

arrPtr = a;    // Error: mismatched pointer types.

The reason is that an array name, such as a, is implicitly converted into a pointer to the array's first element, not a pointer to the whole array. The pointer to int is not implicitly converted into a pointer to an array of int. The assignment in the example requires an explicit type conversion, specifying the target type int (*)[10] in the cast operator:

arrPtr = (int (*)[10])a;     // OK

You can derive this notation for the array pointer type from the declaration of arrPtr by removing the identifier (see "Type Names" in Chapter 11). However, for more readable and more flexible code, it is a good idea to define a simpler name for the type using typedef:

typedef int ARRAY_t[10];     // A type name for "array of ten int elements".
ARRAY_t a,                   // An array of this type,
        *arrPtr;             // and a pointer to this array type.
arrPtr = (ARRAY_t *)a;       // Let arrPtr point to a.

9.4.2. Pointer Arrays

Pointer arraysthat is, arrays whose elements have a pointer typeare often a handy alternative to two-dimensional arrays. Usually the pointers in such an array point to dynamically allocated memory blocks.

For example, if you need to process strings, you could store them in a two-dimensional array whose row size is large enough to hold the longest string that can occur:

#define ARRAY_LEN 100
#define STRLEN_MAX 256
char myStrings[ARRAY_LEN][STRLEN_MAX] =
{ // Several corollaries of Murphy's Law:
  "If anything can go wrong, it will.",
  "Nothing is foolproof, because fools are so ingenious.",
  "Every solution breeds new problems."
};

However, this technique wastes memory, as only a small fraction of the 25,600 bytes devoted to the array is actually used. For one thing, a short string leaves most of a row empty; for another, memory is reserved for whole rows that may never be used. A simple solution in such cases is to use an array of pointers that reference the objectsin this case, the stringsand to allocate memory only for the pointer array and for objects that actually exist. Unused array elements are null pointers.

#define ARRAY_LEN 100
char *myStrPtr[ARRAY_LEN] =    // Array of pointers to char
{ // Several corollaries of Murphy's Law:
  "If anything can go wrong, it will.",
  "Nothing is foolproof, because fools are so ingenious.",
  "Every solution breeds new problems."
};

The diagram in Figure 9-3 illustrates how the objects are stored in memory.

The pointers not yet used can be made to point to other strings at runtime. The necessary storage can be reserved dynamically in the usual way. The memory can also be released when it is no longer needed.

The program in Example 9-4 is a simple version of the filter utility sort. It reads text from the standard input stream, sorts the lines alphanumerically, and prints them to standard output. This routine does not move any strings: it merely sorts an array of pointers.

Figure 9-3. Pointer array


Example 9-4. A simple program to sort lines of text
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *getline(void);             // Reads a line of text
int str_compare(const void *, const void *);

#define NLINES_MAX 1000          // Maximum number of text lines.
char *linePtr[NLINES_MAX];       // Array of pointers to char.

int main( )
{
  // Read lines:
  int n = 0;                     // Number of lines read.
  for (  ; n < NLINES_MAX && (linePtr[n] = getline( )) != NULL; ++n )
    ;

  if ( !feof(stdin) )            // Handle errors.
  {
    if ( n == NLINES_MAX )
      fputs( "sorttext: too many lines.\n", stderr );
    else
      fputs( "sorttext: error reading from stdin.\n", stderr );
  }
  else                           // Sort and print.
  {
    qsort( linePtr, n, sizeof(char*), str_compare );     // Sort.
    for ( char **p = linePtr; p < linePtr+n; ++p )       // Print.
      puts(*p);
  }
  return 0;
}

// Reads a line of text from stdin; drops the terminating newline character.
// Return value: A pointer to the string read, or
//               NULL at end-of-file, or if an error occurred.
#define LEN_MAX 512                           // Maximum length of a line.

char *getline( )
{
  char buffer[LEN_MAX], *linePtr = NULL;
  if ( fgets( buffer, LEN_MAX, stdin ) != NULL )
  {
    size_t len = strlen( buffer );

    if ( buffer[len-1] == '\n' )              // Trim the newline character.
      buffer[len-1] = '\0';
    else
      ++len;

    if ( (linePtr = malloc( len )) != NULL )  // Get enough memory for the line.
      strcpy( linePtr, buffer );        // Copy the line to the allocated block.
  }
  return linePtr;
}

// Comparison function for use by qsort( ).
// Arguments: Pointers to two elements in the array being sorted:
//            here, two pointers to pointers to char (char **).
int str_compare( const void *p1, const void *p2 )
{
  return strcmp( *(char **)p1, *(char **)p2 );
}

The maximum number of lines that the program in Example 9-4 can sort is limited by the constant NLINES_MAX. However, we could remove this limitation by creating the array of pointers to text lines dynamically as well.


Previous Page
Next Page