0

In my program I have the need to copy 2d arrays of lengths array[3][8] and array[3][3]. Because of the way I have had to set my parameters I haven't been able to do this in one function so I instead have 2 currently.

void copyArray(float arrayA[][8], float arrayB[][8])
{
    for (int a = 0; a < 3; a++)
    {
        for (int b = 0; b < 8; b++)
        {
            arrayA[a][b] = arrayB[a][b];
        }
    }
}

void copyArray(float arrayA[][3], float arrayB[][3])
{
    for (int a = 0; a < 3; a++)
    {
        for (int b = 0; b < 3; b++)
        {
            arrayA[a][b] = arrayB[a][b];
        }
    }
}

Is there a way to condense this into one function instead of having these 2 very similar functions?

4
  • 3
    Easier solution: Use std::vector or std::array. If you are stuck using raw arrays, pass the dimensions a and b separately, then you can have a single function for any shaped array. Commented Nov 17, 2014 at 12:55
  • 1
    Use a function template. Commented Nov 17, 2014 at 12:57
  • 1
    While I agree with the previous commenter (to use std::vector or std::array), it could be done by making copyArray a templated function (where the template arguments is size_t for the dimensions). Commented Nov 17, 2014 at 12:57
  • @JoachimPileborg Do you mean memcpy? Commented Nov 17, 2014 at 13:00

1 Answer 1

2

If you pass arrays by reference, you can usefully specify all their dimensions, and if you define a template function, you can use template parameters for those dimensions.

Like this (generalised for the element type as well):

template<typename T, size_t x, size_t y>
void copyArray(T (&arrayA)[x][y], const T (&arrayB)[x][y])
{
    for (int a = 0; a < x; a++)
    {
        for (int b = 0; b < y; b++)
        {
            arrayA[a][b] = arrayB[a][b];
        }
    }
}

This can probably be replaced with a one-liner in C++ 11, but the template would follow the same principle.

Sign up to request clarification or add additional context in comments.

3 Comments

If I may make a suggestion, then you should make arrayB constant.
@JoachimPileborg Right you are. (I even made the "reverse copy" mistake as I was testing that... The shame. The horror.)
This has worked, however I'm unfamiliar with templates. Could you briefly explain what it is doing here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.