Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Array of Pointers in C

Introduction

In C programming, an array of pointers is an array that consists of pointers that point to other variables. This concept is crucial when dealing with dynamic memory allocation, arrays of strings, and more complex data structures. Understanding arrays of pointers can greatly enhance your ability to manipulate data effectively in C.

Declaration and Initialization

An array of pointers is declared in the same way as a regular array, but with an additional asterisk (*) to denote pointers. Here's the syntax:

datatype *arrayName[arraySize];

For example, to create an array of 5 integer pointers:

int *arr[5];

To initialize the array of pointers, you can assign addresses of existing variables to each element of the array:

int a = 10, b = 20, c = 30;
int *arr[3];
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;

Accessing Data through Array of Pointers

Once you have initialized the array of pointers, you can access the data they point to using the dereference operator (*). Here's an example:

#include <stdio.h>

int main() {
    int a = 10, b = 20, c = 30;
    int *arr[3];
    arr[0] = &a;
    arr[1] = &b;
    arr[2] = &c;

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

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

Example: Array of String Pointers

One common use of arrays of pointers is to store an array of strings. Since strings in C are arrays of characters, a pointer to a string is a pointer to a character (char *). Here's an example:

#include <stdio.h>

int main() {
    const char *colors[] = {"Red", "Green", "Blue"};

    for(int i = 0; i < 3; i++) {
        printf("Color[%d] = %s\\n", i, colors[i]);
    }
    return 0;
}

Color[0] = Red
Color[1] = Green
Color[2] = Blue

Dynamic Memory Allocation with Array of Pointers

Arrays of pointers are especially useful when combined with dynamic memory allocation. You can allocate memory for each element of the array at runtime using functions like malloc(). Here's an example:

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

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

    for(int i = 0; i < n; i++) {
        arr[i] = (int *)malloc(sizeof(int));
        *arr[i] = i * 10;
    }

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

Value at arr[0] = 0
Value at arr[1] = 10
Value at arr[2] = 20

Conclusion

Array of pointers is a powerful concept in C programming that allows for efficient data manipulation and dynamic memory allocation. By understanding how to declare, initialize, and use arrays of pointers, you can manage complex data structures and dynamic data more effectively. Practice with different examples to solidify your understanding of this important topic.