Skip to main content

Array of pointers in C

Array of Pointers

An array in which each element is a pointer to a variable of a particular data type.

In other words, each element of the array points to a memory location where a variable of a specific type is stored.

Array of Pointers - Example

#include <stdio.h>

int main()
{
int num1 = 10, num2 = 20, num3 = 30;
int *arr[3];

arr[0] = &num1;
arr[1] = &num2;
arr[2] = &num3;

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

return 0;
}
Output:

Explanation

  • We have declared an array of three integer pointers arr, and we have initialized each pointer to the address of an integer variable.
  • We then print the elements of the array by dereferencing each pointer using the * operator.

Example 2

#include <stdio.h>

int main()
{
int arr[] = {10, 20, 30, 40, 50};
int *ptr[5];
int sum = 0;

// Initialize the pointers in the array
for (int i = 0; i < 5; i++)
{
ptr[i] = &arr[i];
}

// Add up the elements using the pointers
for (int i = 0; i < 5; i++)
{
sum += *ptr[i];
}

printf("The sum is: %d\n", sum);

return 0;
}
Output:

Explanation

  • We start by initializing an integer array arr with five elements.
  • We then declare an array of five integer pointers ptr.
  • We use a loop to initialize each pointer in the ptr array to the address of the corresponding element in the arr array.
  • We then use another loop to iterate over the ptr array and add up the values of each element using the pointers.
  • Finally, we print out the sum.