ArrayCopy

By wade2462 on May 25, 2010

Function to copy one array to another with bounds checking. It does work with all types. Copy this code into a header file called ArrayCopy.h. In main file code do this.

include "ArrayCopy.h"

...
int destinationArray[some size1];
int sourceArray[some size2]= {1,2,3,4,5,6};

CopyArray(destinationArray, source array, some size1, some size2);
...

#ifndef ARRAYCOPY_H
#define ARRAYCOPY_H

#include <iostream>

template <typename type>
void CopyArray( type *tA, type *tB, int aSize, int bSize) // destination, source, size of destination, size of source
{
    if(aSize == bSize)
    { 
        for (int iii = 0; iii < bSize; ++iii)
        {
            tA[iii]= tB[iii];
        }

    }
    else if(aSize > bSize)
    {
        int difference = aSize-bSize;
        int position = aSize-difference;
        for (int iii = 0; iii < bSize; ++iii)
        {
            tA[iii]= tB[iii];
        }
        for (position; position < aSize; ++position)
        {
            tA[position] = 0;
        }
    }
    else if(bSize > aSize)
    {
        for (int iii = 0; iii < aSize; ++iii)
        {
            tA[iii]= tB[iii];
        }
    }
    else
    {
        cerr << "Oops, Something Has Gone Awry. Cannot Copy.";
    }

}

#endif

Comments

Sign in to comment.
Gummo   -  May 27, 2010

It can still be simplified by what I mentioned.. Why'd you delete my comment?

 Respond  
wade2462   -  May 26, 2010

^tried it but gave me errors. Thats what i thought too.

 Respond  
guest598594   -  May 26, 2010
CopyArray(destinationArray, source array, some size1, some size2);

I'm no C++ expert but can't you just get somesize1 and somesize2 from the given arrays?

Edit: found this on google

int arr[17];
int arrSize = sizeof(arr) / sizeof(int);
 Respond  
wade2462   -  May 26, 2010

If sizes are the same copy across. If destination is bigger than fill in zeroes till the end. If source is bigger than cut it off.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.