Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C Program to Calculate Average of an Array
Next article icon

C Program to Copy an Array to Another Array

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to copy all the elements of one array to another array in C.

The simplest method to copy an array is by using the memcpy() function. Let’s take a look at an example:

C
#include <stdio.h> #include <string.h>  int main() {     int arr1[] = {1, 2, 3, 4, 5};     int n = sizeof(arr1) / sizeof(arr1[0]);     int arr2[n];      // Use memcpy to copy arr1 to arr2     memcpy(arr2, arr1, n * sizeof(arr1[0]));      for (int i = 0; i < n; i++)         printf("%d ", arr2[i]);     return 0; } 

Output
1 2 3 4 5 

Explanation: The memcpy() function copied the whole block of arr1 memory to arr2.

This method operators directly on low level memory so it is fast but there are some chances of error if not properly used.

There is also a few more methods to copy all the elements of one array to another. Some of them are as follows:

Table of Content

  • Using a Loop
  • Using Recursion
  • Using Pointers

Using a Loop

This method uses a loop to iterate through the array and assign each element to the corresponding index of another array.

C
#include <stdio.h>  void copyArr(int arr1[], int arr2[], int n) {     for (int i = 0; i < n; i++) {          // Copy each element one by one         arr2[i] = arr1[i];     } }  int main() {     int arr1[] = {1, 2, 3, 4, 5};     int n = sizeof(arr1) / sizeof(arr1[0]);     int arr2[n];    	// Copy arr1 to arr2     copyArr(arr1, arr2, n);        for (int i = 0; i < n; i++)         printf("%d ", arr2[i]);     return 0; } 

Output
1 2 3 4 5 

This method provides more control of the copying process.

Using Recursion

In this method, only one element is copied in one function call. The rest of the elements are then copied by recursively calling the function for next elements.

C
#include <stdio.h>  void copyArr(int arr1[], int arr2[], int n) {     if (n == 0) return;            // Copy the current element     arr2[n - 1] = arr1[n - 1];            // Copy the remaining array     copyArr(arr1, arr2, n - 1); }  int main() {     int arr1[] = {1, 2, 3, 4, 5};     int n = sizeof(arr1) / sizeof(arr1[0]);     int arr2[n];        // Copy elements of arr1 to arr2     copyArr(arr1, arr2, n);      for (int i = 0; i < n; i++)         printf("%d ", arr2[i]);     return 0; } 

Output
1 2 3 4 5 

This method is generally not preferred because it may take more memory as compared to other methods (if tail call optimization is not done).

Using Pointers

This method is similar to the loop method but here, pointers are used instead of array names.

C
#include <stdio.h>  void copyArr(int *arr1, int *arr2, int n) {     for (int i = 0; i < n; i++) {          // Copy each element by dereferencing         *(arr2 + i) = *(arr1 + i);     } }  int main() {     int arr1[] = {1, 2, 3, 4, 5};     int n = sizeof(arr1) / sizeof(arr1[0]);     int arr2[n];      // Copy arr1 to arr2     copyArr(arr1, arr2, n);        for (int i = 0; i < n; i++)         printf("%d ", arr2[i]);      return 0; } 

Output
1 2 3 4 5 


Next Article
C Program to Calculate Average of an Array

L

laxmigangarajula03
Improve
Article Tags :
  • C Language
  • C Programs
  • C Array Programs

Similar Reads

  • C Program to Calculate Average of an Array
    In this article, we will learn how to calculate the average of all elements of an array using a C program. The simplest method to calculate the average of all elements of an array is by using a loop. Let's take a look at an example: [GFGTABS] C #include <stdio.h> float getAvg(int arr[], int n)
    2 min read
  • C Program to Traverse an Array
    Write a C program to traverse the given array that contains N number of elements. Examples Input: arr[] = {2, -1, 5, 6, 0, -3} Output: 2 -1 5 6 0 -3 Input: arr[] = {4, 0, -2, -9, -7, 1} Output: 4 0 -2 -9 -7 1 Different Ways to Traverse an Array in CArrays are versatile data structures and C language
    3 min read
  • C Program To Merge Two Arrays
    Merging two arrays means combining/concatenating the elements of both arrays into a single array. Example Input: arr1 = [1, 3, 5], arr2 = [2, 4, 6]Output: res = [1, 3, 5, 2, 4, 6]Explanation: The elements from both arrays are merged into a single array. Input: arr1 = [10, 40, 30], arr2 = [15, 25, 5]
    3 min read
  • C Program to Sort an Array in Ascending Order
    Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element. The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example:
    3 min read
  • C program to sort an array using pointers
    Given an array of size n, the task is to sort this array using pointers in C. Examples: Input: n = 5, arr[] = {0, 23, 14, 12, 9} Output: {0, 9, 12, 14, 23} Input: n = 3, arr[] = {7, 0, 2} Output: {0, 2, 7} Approach: The array can be fetched with the help of pointers with the pointer variable pointin
    2 min read
  • C Program to Find Common Array Elements Between Two Arrays
    Here we will build a C Program to Find Common Array Elements between Two Arrays. Given two arrays we have to find common elements in them using the below 2 approaches: Using Brute forceUsing Merge Sort and then Traversing Input: array1[] = {8, 2, 3, 4, 5, 6, 7, 1} array2[] = {4, 5, 7, 11, 6, 1} Outp
    4 min read
  • C Program to Delete an Element in an Array
    In this article, we will learn to how delete an element from an array in C. C arrays are static in size, it means that we cannot remove the element from the array memory. But we can logically delete the element by overwriting it and updating the size variable. Delete the Given Element from an ArrayT
    3 min read
  • C Program to Remove All Occurrences of an Element in an Array
    To remove all the occurrences of an element in an array, we will use the following 2 approaches: Using MethodsWithout using methods or With Conditional Statement We will keep the same input in all the mentioned approaches and get an output accordingly. Input: array = {1, 2, 1, 3, 1} value = 1 Output
    3 min read
  • How to Convert a String to a Char Array in C?
    In C, the only difference between the string and a character array is possibly the null character '\0' but strings can also be declared as character pointer in which case, its characters are immutable. In this article, we will learn how to convert a string to a char array in C. The most straightforw
    2 min read
  • How to Pass a 3D Array to a Function in C?
    A 3D array (or three-dimensional array) in C is a multi-dimensional array that contains multiple layers of two-dimensional arrays stacked on top of each other. It stores elements that can be accessed using three indices: the depth index, row index, and column index. In this article, we will learn ho
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences