Home C array of pointers in C tutorial

array of pointers in C tutorial

An array of pointers in C is an array where each element is a pointer, rather than a regular data type like int or char.

This is especially useful for managing collections of strings or dynamically allocated memory blocks, as it allows you to efficiently manage memory for each element in the array.

1. Declaring an Array of Pointers

To declare an array of pointers, specify the type and add * to each element, followed by the size of the array in square brackets.

data_type *array_name[size];

For example:

int *arr[5]; // Array of 5 pointers to int
char *names[3]; // Array of 3 pointers to char

2. Basic Example of Array of Pointers with Strings

A common use case is to create an array of pointers to char, which can store multiple strings.

#include <stdio.h>

int main() {
    const char *fruits[] = {"Apple", "Banana", "Cherry"};

    for (int i = 0; i < 3; i++) {
        printf("Fruit %d: %s\n", i + 1, fruits[i]);
    }

    return 0;
}

Explanation:

  • fruits is an array of pointers, where each element points to a string literal (const char).
  • Each string can be accessed with fruits[i].

Output:

Fruit 1: Apple
Fruit 2: Banana
Fruit 3: Cherry

3. Initializing an Array of Pointers to Integers

An array of pointers to int can hold the addresses of multiple integer variables.

#include <stdio.h>

int main() {
    int a = 10, b = 20, c = 30;
    int *arr[] = {&a, &b, &c};

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

    return 0;
}

Explanation:

  • arr is an array of pointers, where each element points to an integer variable.
  • Dereferencing arr[i] accesses the value of each variable.

Output:

Value of arr[0]: 10
Value of arr[1]: 20
Value of arr[2]: 30

4. Array of Pointers with Dynamic Memory Allocation

Using an array of pointers allows dynamic allocation of memory for each element, which is useful for creating arrays of different sizes.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr[3];

    for (int i = 0; i < 3; i++) {
        arr[i] = (int *)malloc(sizeof(int));
        *arr[i] = (i + 1) * 10; // Assign values 10, 20, 30
    }

    for (int i = 0; i < 3; i++) {
        printf("arr[%d] = %d\n", i, *arr[i]);
        free(arr[i]); // Free each allocated memory
    }

    return 0;
}

Explanation:

  • Each element of arr is dynamically allocated using malloc.
  • Each allocated block is assigned a value and then freed after use.

Output:

arr[0] = 10
arr[1] = 20
arr[2] = 30

5. Array of Pointers to Strings (Using String Literals)

When working with strings, an array of pointers to char is useful for storing multiple string literals.

#include <stdio.h>

int main() {
    const char *cities[] = {"New York", "Los Angeles", "Chicago"};

    for (int i = 0; i < 3; i++) {
        printf("City %d: %s\n", i + 1, cities[i]);
    }

    return 0;
}

Explanation:

  • Each element of cities points to a string literal.
  • You can easily print each string using cities[i].

Output:

City 1: New York
City 2: Los Angeles
City 3: Chicago

6. Modifying Values in an Array of Pointers

You can modify values in an array of pointers by changing the data at the addresses each pointer holds.

#include <stdio.h>

int main() {
    int a = 10, b = 20, c = 30;
    int *arr[] = {&a, &b, &c};

    for (int i = 0; i < 3; i++) {
        *arr[i] += 5; // Increment each value by 5
    }

    printf("Modified values:\n");
    printf("a = %d, b = %d, c = %d\n", a, b, c);

    return 0;
}

Explanation:

  • Modifying *arr[i] directly changes the values of a, b, and c.

Output:

Modified values:
a = 15, b = 25, c = 35

7. Array of Pointers to Arrays (2D Array Representation)

An array of pointers can be used to represent a 2D array, where each pointer points to an array (row) of elements.

#include <stdio.h>

int main() {
    int row1[] = {1, 2, 3};
    int row2[] = {4, 5, 6};
    int row3[] = {7, 8, 9};

    int *matrix[] = {row1, row2, row3};

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

    return 0;
}

Explanation:

  • matrix is an array of pointers, each pointing to a different row array (row1, row2, row3).
  • Each element can be accessed as matrix[i][j].

Output:

1 2 3
4 5 6
7 8 9

8. Array of Pointers to Functions

An array of pointers can also store addresses of functions, allowing you to call different functions based on array indexing.

#include <stdio.h>

void greet() {
    printf("Hello!\n");
}

void farewell() {
    printf("Goodbye!\n");
}

int main() {
    void (*funcArr[2])() = {greet, farewell};

    funcArr[0](); // Calls greet
    funcArr[1](); // Calls farewell

    return 0;
}

Explanation:

  • funcArr is an array of function pointers.
  • funcArr[0] points to greet and funcArr[1] points to farewell.

Output:

Hello!
Goodbye!

9. Passing Array of Pointers to a Function

An array of pointers can be passed to a function to perform operations on each element.

#include <stdio.h>

void printNames(const char *names[], int size) {
    for (int i = 0; i < size; i++) {
        printf("Name %d: %s\n", i + 1, names[i]);
    }
}

int main() {
    const char *names[] = {"Alice", "Bob", "Charlie"};
    printNames(names, 3);

    return 0;
}

Explanation:

  • printNames takes an array of pointers (const char *names[]) as a parameter.
  • Each name is printed by accessing names[i].

Output:

Name 1: Alice
Name 2: Bob
Name 3: Charlie

10. Summary Table of Array of Pointers Examples

Use Case Description Example Code
Array of pointers to strings Stores multiple string literals const char *arr[] = {“Apple”, “Banana”};
Array of pointers to integers Stores addresses of multiple int variables int *arr[] = {&a, &b, &c};
Dynamic memory with array of pointers Allocates memory for each pointer arr[i] = malloc(…);
Modifying values through pointers Modifies original values by dereferencing *arr[i] += 5;
Array of pointers as 2D array Represents rows in a 2D array int *matrix[] = {row1, row2, row3};
Array of function pointers Stores addresses of functions void (*arr[2])() = {func1, func2};
Passing array of pointers to function Passes array of strings to a function void printNames(const char *arr[], int size);

Complete Example: Managing Dynamic Array of Strings

This example demonstrates dynamically allocating memory for an array of strings using an array of pointers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print

Strings(char *arr[], int count) {
    for (int i = 0; i < count; i++) {
        printf("String %d: %s\n", i + 1, arr[i]);
    }
}

int main() {
    int count = 3;
    char *strings[count];

    // Dynamically allocate and assign strings
    for (int i = 0; i < count; i++) {
        strings[i] = (char *)malloc(20 * sizeof(char)); // Allocate memory for each string
        sprintf(strings[i], "String %d", i + 1);        // Assign formatted string
    }

    printStrings(strings, count);

    // Free each allocated string
    for (int i = 0; i < count; i++) {
        free(strings[i]);
    }

    return 0;
}

Explanation:

  • strings is an array of pointers, each pointing to a dynamically allocated memory block that stores a string.
  • printStrings prints each string, and each block of memory is freed after use.

Output:

String 1: String 1
String 2: String 2
String 3: String 3

Using an array of pointers in C allows for flexible memory management and efficient handling of complex data structures, such as dynamic arrays, collections of strings, and function pointers.

You may also like