In this C program, you will learn how to access array elements using pointer.
Program to access array elements using pointer
In this program, we have an array of integers, the name of the array is numbers
. In pointer notation, numbers[0] is equivalent to *numbers. This is because the array name represents the base address (address of first element) of the array.
We already learned in pointer tutorial that * before an address give us the value stored at that address, thus we can say *numbers is equivalent to the numbers[0]. Similarly *(numbers+1) is equivalent to numbers[1] and so on. This logic is used in this program access and print the array elements.
#include <stdio.h>
int main() {
int numbers[5], n=0;
printf("How many elements you would like to enter?: ");
scanf("%d",&n);
printf("Enter elements: ");
for (int i = 0; i < n; ++i)
scanf("%d", numbers + i);
printf("Entered elements: \n");
for (int i = 0; i < n; ++i)
printf("%d\n", *(numbers + i));
return 0;
}
Output: