OneBite.Dev - Coding blog in a bite size

Copy An Array In C++

Code snippet for how to Copy An Array In C++ with sample and detail explanation

When working with objects in C++, there are times when you’ll need to copy an array. This article will break down the process, showing a simple example and providing a detailed explanation.

Code snippet for Copying An Array In C++

#include <iostream>
#include <cstring>

int main() {
    int originalArray[5] = {1, 2, 3, 4, 5}; //source
    int newArray[5]; //target
    memcpy(newArray, originalArray, sizeof(originalArray));
    
    for (int i = 0; i < 5; i++) {
        std::cout << newArray[i] << " ";
    }
    
    return 0;
}

Code Explanation for Copying An Array In C++

The code sample above demonstrates how to make a copy of an array in C++. Let’s break it down step by step.

  1. #include <iostream> and #include <cstring>: These are preprocessor directives which include the input/output stream and C-string library in the code respectively.

  2. int main() { }: This is the main function where the program begins execution.

  3. int originalArray[5] = {1, 2, 3, 4, 5}: Here we declare and initialize an integer array called ‘originalArray.’ The elements of the array are 1, 2, 3, 4, and 5.

  4. int newArray[5]: This declares an integer array called ‘newArray.’ This is where we will copy the elements of ‘originalArray.’

  5. memcpy(newArray, originalArray, sizeof(originalArray)): ‘memcpy’ is a function from the C-string library. It copies the number of bytes provided as the third argument from the source (in this case ‘originalArray’) to the destination (in this case ‘newArray’).

  6. for (int i = 0; i < 5; i++): This is a simple for loop which will iterate through the ‘newArray’.

  7. std::cout << newArray[i] << " ": Inside the for loop, this line prints each element of the newly copied array ‘newArray’ to the console.

  8. return 0: This signifies successful execution of the program.

After executing the code, you should be able to see the elements of ‘newArray’ displayed as “1 2 3 4 5” in the console, which are exactly the same as the elements in the ‘originalArray’.

c-plus-plus