C Program to Copy One Array into Another

C Program to Copy One Array into Another

Copying arrays is a fundamental operation in C programming. Often, you may need to duplicate an array to perform operations on a copy while keeping the original data intact. This task teaches beginners how arrays work in memory, how to access each element, and how standard library functions can simplify programming tasks. In this tutorial, we will cover several ways to copy an array: using loops, using memcpy(), and using memmove(). Each method will be explained in detail, so you understand both the syntax and the logic behind it.

Understanding multiple methods to copy arrays gives you flexibility in writing efficient programs. While loops provide a clear, step-by-step approach suitable for beginners, library functions like memcpy offer faster and more concise ways to copy memory blocks. By the end of this tutorial, you will know when to use each approach, how to write the code correctly, and how to avoid common mistakes.

Copying Arrays Using a Simple Loop

Let’s start with the most basic approach, which is using a for loop. This method allows you to copy each element individually, ensuring complete control over the process.

#include <stdio.h>

int main() {

    int n, i;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int original[n], copy[n];

    printf("Enter %d elements: ", n);

    for(i = 0; i < n; i++) {
        scanf("%d", &original[i]);
    }

    for(i = 0; i < n; i++) {
        copy[i] = original[i]; // Copy each element manually
    }

    printf("Original array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", original[i]);
    }

    printf("\nCopied array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", copy[i]);
    }

    printf("\n");

    return 0;

}

In this code, we first include the stdio.h library for input and output operations. After reading the array size from the user, we declare two arrays: original and copy. The first loop reads values into original, while the second loop duplicates each element into copy. Finally, we print both arrays to confirm that the copy was successful. This method is simple, safe, and ideal for beginners.

Copying Arrays Using memcpy()

The C standard library provides the memcpy() function, which copies a block of memory from one location to another. This method is faster for large arrays because it copies memory directly without the overhead of looping in C code.

#include <stdio.h>
#include <string.h> // Required for memcpy

int main() {

    int n, i;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int original[n], copy[n];

    printf("Enter %d elements: ", n);

    for(i = 0; i < n; i++) {
        scanf("%d", &original[i]);
    }

    memcpy(copy, original, n * sizeof(int)); // Copy the entire array in memory

    printf("Original array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", original[i]);
    }

    printf("\nCopied array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", copy[i]);
    }

    printf("\n");

    return 0;

}

Here, memcpy(copy, original, n * sizeof(int)) copies n integers from original to copy. The sizeof(int) ensures that the correct number of bytes per element is copied. Unlike loops, memcpy directly manipulates memory, making it faster for large arrays. However, memcpy assumes that the memory areas do not overlap.

Copying Arrays Using memmove()

In situations where memory areas might overlap, memmove() is safer than memcpy(). It ensures that the source array is not overwritten before copying completes.

#include <stdio.h>
#include <string.h> // Required for memmove

int main() {

    int n, i;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int original[n], copy[n];

    printf("Enter %d elements: ", n);

    for(i = 0; i < n; i++) {
        scanf("%d", &original[i]);
    }

    memmove(copy, original, n * sizeof(int)); // Safe copy even if memory overlaps

    printf("Original array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", original[i]);
    }

    printf("\nCopied array: ");

    for(i = 0; i < n; i++) {
        printf("%d ", copy[i]);
    }

    printf("\n");

    return 0;

}

memmove(copy, original, n * sizeof(int)) works like memcpy but ensures safe copying even when the source and destination memory overlap. While this is rarely an issue for separate arrays, memmove is useful in more complex programs with shared memory regions.

Common Beginner Mistakes

When copying arrays in C, beginners often make these mistakes:

  • Trying to assign arrays directly, such as copy = original;, which is not allowed in C.
  • Not allocating enough memory for the copy or miscalculating the number of bytes in memcpy or memmove.
  • Forgetting to include the <string.h> header, which is required for memory functions.
  • Confusing memcpy with memmove; memcpy can produce incorrect results if the source and destination memory overlap.

To avoid these issues, always allocate sufficient memory, include the proper headers, and choose memmove when handling overlapping memory regions.

FAQs

Q1: Can memcpy be used for non-integer arrays?
Yes, memcpy works for any data type, including float, double, or structs, as long as you multiply the number of elements by the size of each element.

Q2: When should I use memmove instead of memcpy?
Use memmove when the source and destination memory regions might overlap. For separate arrays, memcpy is faster and sufficient.

Q3: Can I copy multi-dimensional arrays this way?
Yes, but you must calculate the total number of elements and multiply by the size of each element. Loops are often easier to read for multi-dimensional arrays.

Q4: Why not just use loops for everything?
Loops are clear and beginner-friendly. However, library functions like memcpy are optimized and faster for large data, especially when performance matters.

Conclusion

Copying arrays is a core concept in C programming. Beginners benefit from understanding how to duplicate arrays using loops, memcpy, and memmove. Loops give a clear, element-by-element copy, while library functions provide faster, more efficient ways to copy memory. Practicing these methods helps you understand memory layout and array manipulation, which are essential skills for any C programmer.

References & Additional Resources

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language. 2nd Edition, Prentice Hall, 1988.
  2. GeeksforGeeks: Copy Array in C – Step-by-step guide with examples.
  3. TutorialsPoint: Arrays in C – In-depth array tutorial.
  4. Programiz: C Programming Examples – Beginner-friendly code examples.
  5. Stack Overflow: Copy Array in C – Discussion on array copy techniques.
Scroll to Top