• Home
  • 5.15 Array of Pointers

5.15 Array of Pointers

View Categories

5.15 Array of Pointers

An array of pointers stores multiple pointer values, with each element holding the address of an object. The pointer type determines the type of object each element can point to.

#include <stdio.h>

int main(void)
{
    int a = 10;
    int b = 20;
    int c = 30;

    int *ptrs[3] = {&a, &b, &c};

    for (int i = 0; i < 3; i++)
    {
        printf("%d\n", *ptrs[i]);
    }

    return 0;
}

Example Output #

10
20
30

Explanation #

The declaration:

int *ptrs[3];

creates an array containing three pointers to int. Each element can store the address of an integer object.

The initialization:

int *ptrs[3] = {&a, &b, &c};

stores the addresses of a, b, and c in the array.

The expression:

*ptrs[i]

dereferences the pointer at index i to access the integer value it points to.

Array of Pointers vs. Pointer to an Array #

Declaration Meaning
int *ptrs[3]; Array of three pointers to int
int (*ptr)[3]; Pointer to an array of three int elements
int *ptr; Pointer to a single int

Parentheses affect how the declaration is interpreted. In int *ptrs[3], the array subscript binds more tightly than the pointer declarator, so ptrs is an array of pointers.

An array of pointers is useful for storing addresses of separate variables, selecting among buffers, and managing arrays of strings. Each pointer must point to a valid object before it is dereferenced.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *