In this article, we are going to learn how to copy one array to another using pointer. We will ask the user to input the elements of the array and iterate over the element of the array and copy one array to another array
C program to copy an array to another array using pointers
In this example, we are taking the array size and array elements as inputs from users by using the pointers.
Then we are iterating over the array to copy its elements to another array of the same size.
- Taking array input from the user
- Iterate over the elements of the array.
- Copy the input array element to another array
#include <stdio.h>
#define SIZE 100
int main()
{
int arr1[SIZE];
int arr2[SIZE]= {0};
int size;
int *arr1StartIndex = arr1;
int *arr2StartIndex = arr2;
int *arr1EndIndex;
printf("Please enter size of array(max 100): ");
scanf("%d", &size);
printf("Please enter elements of array:\n");
for (int i = 0; i < size; i++)
{
scanf("%d", (arr1StartIndex + i));
}
printf("The elements of array 1 entered by user are: \n");
for (int k = 0; k < size; k++)
{
printf("Index [%d]= %d, \n",k, *arr1StartIndex);
arr1StartIndex++;
}
arr1StartIndex = arr1;
arr1EndIndex = &arr1[size - 1];
while(arr1StartIndex <= arr1EndIndex)
{
*arr2StartIndex = *arr1StartIndex;
arr1StartIndex++;
arr2StartIndex++;
}
arr2StartIndex = arr2;
printf("The elements of Array2 after Copy from Array 1 are: \n");
for (int k = 0; k < size; k++)
{
printf("Index [%d]= %d, \n",k, *arr2StartIndex);
arr2StartIndex++;
}
return 0;
}
Output
Please enter size of array(max 100): 5
Please enter elements of array:
1
2
3
4
5
The elements of array 1 entered by user are:
Index [0]= 1,
Index [1]= 2,
Index [2]= 3,
Index [3]= 4,
Index [4]= 5,
The elements of Array2 after Copy from Array 1 are:
Index [0]= 1,
Index [1]= 2,
Index [2]= 3,
Index [3]= 4,
Index [4]= 5,