Copy one array to another using pointers

C program to copy one array to another using pointers

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50

void print_array(int arr[], int n);

void main()
{
	int arr1[MAX], arr2[MAX];
    int n, i;
    int *ptr1, *ptr2;

    printf("Enter the size of the array\t:");
    scanf("%d",&n);

    printf("\nEnter elements in the array\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr1[i]);
    }

    ptr1 = arr1;      //pointer ptr1 points to arr1[0]
    ptr2 = arr2;      //pointer ptr2 points to arr2[0]

    printf("\nSource array before copying: ");
    print_array(arr1, n);

    printf("\nDestination array before copying: ");
    print_array(arr2, n);

    for(i=0;i<n;i++)
    {
        *ptr2 = *ptr1;
        *ptr1++;
        *ptr2++;
    }

    printf("\n\nSource array after copying: ");
    print_array(arr1, n);

    printf("\nDestination array after copying: ");
    print_array(arr2, n);

    getch();
}

void print_array(int *arr, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("%d ",arr[i]);
    }
}

Output

Enter the size of the array     :5

Enter elements in the array
1
2
3
4
5

Source array before copying: 1 2 3 4 5
Destination array before copying: 16 18612224 12451840 2 72

Source array after copying: 1 2 3 4 5
Destination array after copying: 1 2 3 4 5

Explanation

In the above program, we have to copy one array to another array using pointers. For this purpose, number of elements in the array 'n' and elements of the array 'arr1' are taken as an input from the user. Another array 'arr2' is declared to store the copy of arr1. Two pointers 'ptr1' and 'ptr2' are declared and points to array 'arr1' and array 'arr2' respectively.
ptr1 = arr1;
ptr2 = arr2;

To copy the array 'arr1' to array 'arr2', following procedure is followed.
Copy elements from 'ptr1' to 'ptr2' using the statement
*ptr2 = *ptr1;
Pointers 'ptr1' and 'ptr2' are incremented by 1, so that, they point to the next element of their respective arrays.
ptr1++;
ptr2++;
The above procedure is repeated 'n' number of times


To print the arrays, print_array() function is used. This function takes array 'arr' and number of elements in the array 'n' as arguments