Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Access Array Elements Using Pointer

C Code Example — Function Programs

ADVERTISEMENT

C Program to Access Array Elements Using Pointer

Objective

Write a C program to access array elements using Pointers.

Algorithm / Approach

  1. Declare an array arr[5].
  2. Use a loop to read input. Instead of &arr[i], use pointer arithmetic: scanf("%d", arr + i).
  3. Use another loop to print output. Instead of arr[i], dereference the calculated memory address: printf("%d", *(arr + i)).
main.c
#include<stdio.h>
int main( ) {
 int arr[5], i;
 printf("Enter Elements of Array:");
 for(i=0;i<5;i++){
  scanf("%d",arr+i);
 }
  printf("You have entered : ");
 for(i=0;i<5;i++){
   printf("%d ",*(arr+i));
 }
 return 0;
}

Expected Output

Enter Elements of Array : 1 4 6 7 8
You have entered : 1 4 6 7 8

Explanation of the Program

  • This proves that array indexing (arr[i]) is just "syntactic sugar" for pointer arithmetic.
  • Under the hood, when you write arr[i], the compiler translates it to *(arr + i): take the base memory address of the array, move forward i integer slots in memory, and fetch the data there.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT