0
0
CHow-ToBeginner · 3 min read

How to Use Array of Pointers in C: Syntax and Examples

In C, an array of pointers is declared by specifying a pointer type followed by square brackets, like int *arr[5];. Each element in this array holds the address of an integer, allowing indirect access to multiple variables or arrays. You use it by assigning addresses to each pointer and then dereferencing them to access or modify the values.
📐

Syntax

An array of pointers is declared by specifying the pointer type followed by the array size in square brackets. For example, int *arr[5]; declares an array of 5 pointers to integers.

  • int *: pointer to an integer
  • arr[5]: array of 5 elements
  • Each element arr[i] holds the address of an int

You can assign addresses to each pointer and access the pointed values using the dereference operator *.

c
int *arr[5];
💻

Example

This example shows how to declare an array of pointers, assign addresses of integer variables to it, and access their values through the pointers.

c
#include <stdio.h>

int main() {
    int a = 10, b = 20, c = 30;
    int *arr[3];  // array of 3 pointers to int

    arr[0] = &a;  // assign address of a
    arr[1] = &b;  // assign address of b
    arr[2] = &c;  // assign address of c

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

    return 0;
}
Output
Value at arr[0] = 10 Value at arr[1] = 20 Value at arr[2] = 30
⚠️

Common Pitfalls

Common mistakes when using arrays of pointers include:

  • Not initializing pointers before dereferencing, which causes undefined behavior.
  • Confusing int *arr[5] (array of pointers) with int (*arr)[5] (pointer to an array).
  • Assigning values directly to pointers instead of addresses.

Always assign valid addresses to pointers before using them.

c
#include <stdio.h>

int main() {
    int a = 5;
    int *arr[1];

    // Wrong: assigning value instead of address
    // arr[0] = a;  // This is incorrect

    // Right: assign address
    arr[0] = &a;

    printf("Value: %d\n", *arr[0]);
    return 0;
}
Output
Value: 5
📊

Quick Reference

  • Declaration: type *arrayName[size];
  • Assign address: arrayName[index] = &variable;
  • Access value: *arrayName[index]
  • Use loops to iterate over pointers
  • Initialize pointers before use to avoid errors

Key Takeaways

Declare an array of pointers with syntax like int *arr[5]; to hold addresses of integers.
Assign valid addresses to each pointer before dereferencing to avoid undefined behavior.
Use the dereference operator * on array elements to access or modify the pointed values.
Do not confuse array of pointers with pointer to an array; their syntax and usage differ.
Loops help efficiently access multiple pointers in the array.