Array of Pointers in C
An array of pointers in C is an array where each element is a pointer to another data type, rather than a data type itself. This allows you to create arrays of various data types dynamically and is particularly useful when dealing with arrays of strings or arrays of complex structures.
#include <stdio.h>
int main() {
int num1 = 10, num2 = 20, num3 = 30;
// Declare an array of integer pointers
int* numArray[3];
// Assign the addresses of integers to the array elements
numArray[0] = &num1;
numArray[1] = &num2;
numArray[2] = &num3;
// Access and print the values using the pointers
for (int i = 0; i < 3; i++) {
printf("Value at numArray[%d]: %d\n", i, *numArray[i]);
}
return 0;
}
Output:
Value at numArray[0]: 10
Value at numArray[1]: 20
Value at numArray[2]: 30
In this example:
- We declare three integer variables:
num1
, num2
, and num3
, each with different integer values.
- We declare an array of integer pointers
int* numArray[3]
. This array can hold three pointers to integers.
- We assign the addresses of the integer variables to the elements of the
numArray
using the &
operator.
- We use a
for
loop to access and print the values of the integers using the pointers stored in the numArray
.
You can create arrays of pointers to other data types (e.g., double
, char
, or custom structures) following a similar pattern. An array of pointers is a powerful concept that allows you to work with dynamically allocated data and collections of various types efficiently.