This example demonstrates another similarity between arrays and pointers. Array elements can be accessed using pointer arithmetic because the array name represents the base address of the array.
#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50};
int *ptr;
int i;
ptr = a;
for (i = 0; i < 5; i++)
{
printf("%d ", *ptr++);
}
printf("\n");
for (i = 0; i < 5; i++)
{
printf("%d ", *(a + i));
}
printf("\n");
return 0;
}
Output:
10 20 30 40 50
10 20 30 40 50
ptr is a pointer variable initialized with the address of the first element of the array.
In the first loop:
*ptraccesses the current elementptr++moves the pointer to the next integer element
In the second loop:
*(a + i)
accesses array elements using pointer arithmetic.
a + i calculates the address of the ith element from the base address of the array, and * dereferences that address to fetch the value.
This shows that array indexing internally works using pointer arithmetic. For example:
a[i]
is equivalent to:
*(a + i)
The array name behaves like a pointer to the first element, but unlike a normal pointer variable, the array name itself cannot be modified.