Skip to main content

Using Pointers and Arrays in C

Pointers and Arrays

Arrays are implemented using pointers. An array name is a constant pointer to the first element of the array.

This means that you can use array syntax to access the elements of the array, or you can use pointer arithmetic to access the elements of the array.

Pointers and Arrays - Example

#include <stdio.h>

int main()
{
int arr[5] = {1, 2, 3, 4, 5};

// Accessing the array using array syntax
printf("Array elements: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
printf("\n");

// Accessing the array using pointer arithmetic
printf("Array elements using pointers: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", *(arr + i));
}
printf("\n");

return 0;
}
Output:

Explanation

  • An integer array arr is initialized with five elements.
  • The array is then accessed using both array syntax and pointer arithmetic.
  • In the first loop, array syntax is used to access the elements of the array.
  • In the second loop, pointer arithmetic is used to access the elements of the array by dereferencing the pointer arr + i, which points to the ith element of the array.
  • Note that *(arr + i) is equivalent to arr[i].