C Program to Access Array Elements Using Pointer
Example: Access Array Elements Using Pointers
#include <stdio.h>
int main()
{
int data[5], i;
printf("Enter elements: ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for(i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}Output
Enter elements: 1 2 3 5 4 You entered: 1 2 3 5 4
In this program, the elements are stored in the integer array data.
Then, using the for loop, each element in the data is traversed and printed using the pointer method.
a step-by-step explanation of a C program that accesses array elements using a pointer:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // declare and initialize an integer array
int *ptr = arr; // declare and initialize an integer pointer to point to the first element of the array
for (int i = 0; i < 5; i++) {
printf("Value of arr[%d] = %d\n", i, *(ptr + i)); // access each element using pointer arithmetic
}
return 0;
}
Let’s break it down step-by-step:
We include the necessary header file
stdio.hfor input/output functions.We declare an integer array
arrof size 5 and initialize it with some values.We declare an integer pointer
ptrand initialize it to point to the first element of the arrayarrusingptr = arr.We use a
forloop to iterate over all the elements of the arrayarr.Inside the loop, we use pointer arithmetic to access each element of the array. We use the expression
*(ptr + i)to access the element at the indexiof the arrayarr.We print the value of each element of the array using
printf().Finally, we return 0 to indicate successful completion of the program.