C program to copy one array to another using pointers
Here, you will learn how to write a C program to copy one array element to another array using pointers.
Step-by-step guide to copy one array to another
The given points describe the step-by-step logic to copy one array to another using pointers.
- Input the size of the first array and store it in a variable say size.
- Declare two arrays, the first source array source_arr and a destination array destination_arr.
- Input the source array elements.
- Declare pointers to the source and destination arrays named src_ptr and dest_ptr.
- Copy elements from src_ptr to dest_ptr using *dest_ptr = *src_ptr
- Increment pointers source_ptr and desc_ptr by 1.
- Display the destination array.
#include <stdio.h>
int main() {
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int source_arr[size];
int destination_arr[size];
int *src_ptr = source_arr;
int *dest_ptr = destination_arr;
// Input the source array elements.
printf("Enter the elements: ");
for (int i = 0; i < size; i++) {
scanf("%d", &(*(source_arr + i)));
}
// Copy elements using pointers
for (int i = 0; i < size; i++) {
*(dest_ptr + i) = *(src_ptr + i);
}
// Display the destination array
printf("Copied Array: \n");
for (int i = 0; i < size; i++) {
printf("%d\n", destination_arr[i]);
}
return 0;
}
Output of the above code:
Enter the size of array: 5
Enter the elements: 2 6 4 9 1
Copied Array:
2
6
4
9
1
Related Articles
Convert double to int JavaAverage of two numbers in C
Swapping of two numbers in C using pointers
Armstrong number in C using function
Binary to decimal C program
Sum of array elements in C
Random number generator in C
Factorial program in c using while loop
Student mark sheet program in C
C program to sort names in alphabetical order
C program to find largest number in an array
Print first 10 natural numbers using while loop in C
Simple calculator program in C
C program for simple interest
Swap two numbers without using third variable in C
Radix sort program in C
Bit stuffing program in C
Bubble sort program in C
Decimal to hexadecimal in C
Hexadecimal to decimal in C
Quick sort program in C