Is There a Function to Copy an Array in C/C++

Is there a function to copy an array in C/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

How do I correctly create a copy of an array in C or set a reference to one?

Ignoring that doing a hard copy of the data is incredibly slow and wasteful, it is also incorrect indeed.

memcpy(activeCommand, stepsToRun, sizeof(activeCommand));

Here you need to copy the size of the data you pass on, not the size of the target buffer! Right now you end up copying more data than you have, because all of these declarations static const command rollDay[] etc get a variable size depending on the number of items in the initializer list.

The quick & dirty fix to your immediate problem would be to pass along the size:

void RunOnce(size_t size, command stepsToRun[size])
{
memcpy(activeCommand, stepsToRun, size);

and then call this function with RunOnce(sizeof rollDay, rollDay); etc.

The activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]); part is also incorrect but not the immediate reason for the bug. See How to find the 'sizeof' (a pointer pointing to an array)? and What is array to pointer decay? etc.

is there any way to copy double type arrays

There is no built-in way to copy arrays in C directly.

You have two options:

  1. The loop you mentioned:

    for(i = 0; i < n; i++) {
        b[i] = a[i];
    }
  2. The memcpy function:

    memcpy(b, a, n * sizeof(double));

Is there a function to copy an array in C/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



Related Topics



Leave a reply



Submit