Access Array Elements Using Pointer in C

Exercise:

Write a C Program to access array elements using pointer.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int data[5];
    printf("Enter elements: ");
    for (int i = 0; i < 5; ++i) {
        scanf("%d", data + i);
    }
    printf("Entered Array is as follows: \n");
    for (int i = 0; i < 5; ++i) {
        printf("%d\n", *(data + i));
    }
    return 0;
}
Click Here to View the Output!
Enter elements: 1 5 2 6 3 4 
Entered Array is as follows: 
1
5
2
6
3
Click Here to View the Explanation!
  • This program is used to access the elements of an array by using a Pointer.
  • In main(), an integer array data is initialized of size 5.
  • The program requests the user to enter the elements inside the array and stores them in the ith location of the array according to the iteration. Since, data+i means &data[i] where & (ampersand) points at the location of the array.
  • Next, the program accesses and prints all the elements of the array by using a pointer *(data + i). Since, *(data + i) means data[i] where * (pointer) points at the value in an array placed at a specific index.
%d bloggers like this: