Skip to main content

Array of pointers

Short answer

An array of pointers stores memory addresses as elements. Declared as data_type *name[size]; it is commonly used for arrays of strings or command-line arguments, allowing efficient manipulation like sorting by swapping only pointers, not the actual data.

Briefly explain array of pointers.

An array of pointers is an array whose elements are all pointers, each holding the address of a variable or a string.

Declaration: data_type *name[size]; for example int *p[3]; is an array of 3 pointers to integers.

int x = 10, y = 20, z = 30;
int *p[3] = {&x, &y, &z};     /* p[i] stores the address of x, y, z */
printf("%d", *p[1]);          /* prints 20 */

The commonest use is an array of strings, where each pointer points to a string, and strings of different lengths need no wasted space:

char *day[3] = {"Sunday", "Monday", "Tuesday"};

Sorting these strings only needs the pointers to be swapped, not the characters. It is also used for arrays of structure pointers and argv (command line arguments).

#include <stdio.h>

int main(void)
{
    char *day[3] = {"Sunday", "Monday", "Tuesday"};   /* array of 3 pointers */
    int x = 10, y = 20, z = 30;
    int *p[3] = {&x, &y, &z};

    for (int i = 0; i < 3; i++)
        printf("%s  %d\n", day[i], *p[i]);
    return 0;
}

Output:

Sunday  10
Monday  20
Tuesday  30

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →