Loading, please wait...

Array of Pointers

Arrays may contain pointers. A common use of an array of pointers is to form an array of strings, referred to simply as a string array. Each entry in the array is a string, but in C a string is essentially a pointer to its first character. So each entry in an array of strings is actually a pointer to the first character of a string.

 

Consider the definition of string array suit, which might be useful in representing a deck of cards.

const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };

The suit[4] portion of the definition indicates an array of 4 elements. The char * portion of the declaration indicates that each element of array suit is of type “pointer to char.” Qualifier const indicates that the strings pointed to by each element pointer will not be modified. The four values to be placed in the array are "Hearts", "Diamonds", "Clubs" and "Spades".

 

Each is stored in memory as a null-terminated character string that is one character longer than the number of characters between quotes. The four strings are 7, 9, 6 and 7 characters long, respectively. Although it appears as though these strings are being placed in the suit array, only pointers are actually stored in the array 

 

Each pointer points to the first character of its corresponding string. Thus, even though the suit array is fixed in size, it provides access to character strings of any length. This flexibility is one example of C’s powerful data structuring capabilities.

 

Figure

 

 

 

 

The suits could have been placed in a two-dimensional array, in which each row would represent a suit and each column would represent a letter from a suiting name. Such a data structure would have to have a fixed number of columns per row, and that number would have to be as large as the largest string.

 

Therefore, considerable memory could be wasted when a large number of strings were being stored with most strings shorter than the longest string.