Is there a function to copy an array in C/C++?

C++CArrays

C++ Problem Overview


I am a Java programmer learning C/C++. So I know that Java has a function like System.arraycopy(); to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementation to copy an array by using for loop, pointers,etc. Is there a function that I can use to copy an array?

C++ Solutions


Solution 1 - C++

Since you asked for a C++ solution...

#include <algorithm>
#include <iterator>

const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));

Solution 2 - C++

Since C++11, you can copy arrays directly with std::array:

std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B

Here is the documentation about std::array

Solution 3 - C++

As others have mentioned, in C you would use memcpy. Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.

In C++ you can also use memcpy if your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpy will not be allowed. As others mentioned, the function to use is std::copy.

Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers (std::vector is the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::deque or std::list may be more appropriate in some cases) or, if you use C++11, std::array which is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.

This gives an overview of the possibilities (I assume all relevant headers have been included):

int main()
{
  // This works in C and C++
  int a[] = { 1, 2, 3, 4 };
  int b[4];
  memcpy(b, a, 4*sizeof(int)); // int is a POD

  // This is the preferred method to copy raw arrays in C++ and works with all types that can be copied:
  std::copy(a, a+4, b);

  // In C++11, you can also use this:
  std::copy(std::begin(a), std::end(a), std::begin(b));

  // use of vectors
  std::vector<int> va(a, a+4); // copies the content of a into the vector
  std::vector<int> vb = va;    // vb is a copy of va

  // this initialization is only valid in C++11:
  std::vector<int> vc { 5, 6, 7, 8 }; // note: no equal sign!

  // assign vc to vb (valid in all standardized versions of C++)
  vb = vc;

  //alternative assignment, works also if both container types are different
  vb.assign(vc.begin(), vc.end());

  std::vector<int> vd; // an *empty* vector

  // you also can use std::copy with vectors
  // Since vd is empty, we need a `back_inserter`, to create new elements:
  std::copy(va.begin(), va.end(), std::back_inserter(vd));

  // copy from array a to vector vd:
  // now vd already contains four elements, so this new copy doesn't need to
  // create elements, we just overwrite the existing ones.
  std::copy(a, a+4, vd.begin());

  // C++11 only: Define a `std::array`:
  std::array<int, 4> sa = { 9, 10, 11, 12 };

  // create a copy:
  std::array<int, 4> sb = sa;

  // assign the array:
  sb = sa;
}

Solution 4 - C++

Use memcpy in C, std::copy in C++.

Solution 5 - C++

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove() copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

Solution 6 - C++

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

So, the C++ solution where the arrays are defined as pointers:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersize with 1:

> 1) Copies all elements in the range [first, last) starting from first and proceeding to last - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

Solution 7 - C++

In C you can use memcpy. In C++ use std::copy from the <algorithm> header.

Solution 8 - C++

Just include the standard library in your code.

#include<algorithm>

Array size will be denoted as n

Your old Array

int oldArray[n]={10,20,30,40,50};

Declare New Array in which you have to copy your old array value

int newArray[n];

Use this

copy_n(oldArray,n,newArray);

Solution 9 - C++

in C++11 you may use Copy() that works for std containers

template <typename Container1, typename Container2>
auto Copy(Container1& c1, Container2& c2)
    -> decltype(c2.begin())
{
	auto it1 = std::begin(c1);
	auto it2 = std::begin(c2);

	while (it1 != std::end(c1)) {
		*it2++ = *it1++;
	}
	return it2;
}

Solution 10 - C++

I give here 2 ways of coping array, for C and C++ language. memcpy and copy both ar usable on C++ but copy is not usable for C, you have to use memcpy if you are trying to copy array in C.

#include <stdio.h>
#include <iostream>
#include <algorithm> // for using copy (library function)
#include <string.h> // for using memcpy (library function)


int main(){

    int arr[] = {1, 1, 2, 2, 3, 3};
    int brr[100];

    int len = sizeof(arr)/sizeof(*arr); // finding size of arr (array)

    std:: copy(arr, arr+len, brr); // which will work on C++ only (you have to use #include <algorithm>
    memcpy(brr, arr, len*(sizeof(int))); // which will work on both C and C++

    for(int i=0; i<len; i++){ // Printing brr (array).
        std:: cout << brr[i] << " ";
    }

    return 0;
}

Solution 11 - C++

Firstly, because you are switching to C++, vector is recommended to be used instead of traditional array. Besides, to copy an array or vector, std::copy is the best choice for you.

Visit this page to get how to use copy function: http://en.cppreference.com/w/cpp/algorithm/copy

Example:

std::vector<int> source_vector;
source_vector.push_back(1);
source_vector.push_back(2);
source_vector.push_back(3);
std::vector<int> dest_vector(source_vector.size());
std::copy(source_vector.begin(), source_vector.end(), dest_vector.begin());

Solution 12 - C++

Try this :

  1. Create an empty array.
  2. Insert the elements.
  3. Create a duplicate empty array of the same size.
  4. Start for i=0 to i=array length.
    5. newarray[i]=oldarray[i] (only for C++)

C++ program

#include<iostream>
using namespace std;
int main()
{
        int initA[100],finA[100],i,size;
        cout<<"Input the size of the array : ";
        cin>>size;
        cout<<"Input the elements of the first array";
        for(i=0;i<size;i++)
        {
               cin>>initA[i];
        }
        for(i=0;i<size;i++)
        {
             finA[i]=initA[i];
        }
        cout<<"The final array is\n";
        for(i=0;i<size;i++)
               cout<<finA[i]<<" ";
        return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ LView Question on Stackoverflow
Solution 1 - C++Ed S.View Answer on Stackoverflow
Solution 2 - C++taocpView Answer on Stackoverflow
Solution 3 - C++celtschkView Answer on Stackoverflow
Solution 4 - C++user541686View Answer on Stackoverflow
Solution 5 - C++DeepuView Answer on Stackoverflow
Solution 6 - C++DrumMView Answer on Stackoverflow
Solution 7 - C++Pete BeckerView Answer on Stackoverflow
Solution 8 - C++Ankit SinghView Answer on Stackoverflow
Solution 9 - C++MORTALView Answer on Stackoverflow
Solution 10 - C++Farid ChowdhuryView Answer on Stackoverflow
Solution 11 - C++Nhan Nguyen Tri ThanhView Answer on Stackoverflow
Solution 12 - C++Deepak Kumar UpadhayayView Answer on Stackoverflow