• Home
  • 5.16 Pointer to an Array

5.16 Pointer to an Array

View Categories

5.16 Pointer to an Array

A pointer to an array stores the address of an entire array rather than the address of an individual element. Parentheses in the declaration distinguish a pointer to an array from an array of pointers.

#include <stdio.h>

int main(void)
{
    int numbers[3] = {10, 20, 30};

    int (*ptr)[3] = &numbers;

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

    return 0;
}

Example Output #

10
20
30

Explanation #

The declaration:

int (*ptr)[3] = &numbers;

declares ptr as a pointer to an array of three integers.

The parentheses around *ptr are essential. Without them, the declaration has a different meaning.

(*ptr)[i]

first dereferences ptr to access the array, then selects the element at index i.

Array and Pointer Declarations #

Declaration Meaning
int numbers[3]; Array of three integers
int *ptr; Pointer to an integer
int *ptrs[3]; Array of three pointers to integers
int (*ptr)[3]; Pointer to an array of three integers

Pointer Arithmetic #

Because ptr points to an entire array of three integers, incrementing it advances by the size of that entire array.

printf("%p\n", (void *)ptr);
printf("%p\n", (void *)(ptr + 1));

The difference between these addresses corresponds to sizeof(numbers) bytes when expressed as addresses of consecutive array positions in a valid array-of-arrays context. In this example, ptr + 1 is a one-past pointer, so it may be formed but must not be dereferenced.

A pointer to an array is useful when working with multidimensional arrays, passing rows to functions, and performing pointer arithmetic over fixed-size groups of elements.

Powered by BetterDocs

Leave a Reply

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