Read and Write an Array Using the Pointer

Relation between Array and Pointer

In C programming, the name of the array always points to address of the first element of an array So, &arr[0] is equivalent to arr. Since the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)

Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1)
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2)
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3)
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i)

C Program to Read and write an array using the pointer

#include<stdio.h>
int main()
{
   int x[5], i;
   int *pa;
   pa = &x[0]; // or, pa = &x;

   printf("Enter array element: ");
   for(i=0;i<5;i++)
   {
     scanf("%d", (pa+i)); 
   }

   printf("Displaying Array: ");
   for(i=0;i<5;i++)
   {
     printf("%d\t",*(pa+i));
   }

   printf("\n");

   return 0;
}

Output:-

Enter array element: 5
10
15
20
25
Displaying Array: 5 10 15 20 25

Read and write an array using function and pointer

#include<stdio.h>
void read(int *p);
void display(int *q);
int main()
{
   int a[5];

   read( &a[0] );
   display( &a[0] );

   return 0;
}

void read(int *p)
{
   int i;

   printf("Enter array elements: ");
   for(i=0;i<5;i++)
   {
      scanf("%d",p+i);
   }
}

void display(int *q)
{
   int i;

   printf("Array elements are:\n");
   for(i=0;i<5;i++)
   {
      printf("%d\t",*(q+i));
   }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Similar C programs on Pointers

Leave a Comment

Your email address will not be published. Required fields are marked *