Search code examples
c++pointersfunction-callfunction-declarationstdarray

Using pointers to copy an array


I'm trying to copy the contents of array1 to array2 using a self-written function called ArrayCopy(). The arrays are both the same size. I have to use pointers to do it.

I know that the integers in array1 are copying over to array2, but when I print array2 outside of the ArrayCopy() function, it still prints with all 0s. I know array1 is successfully getting values from cin.

I cannot change the block of code at the end of main(), otherwise I will lose points on the assignment.

Part of ArrayCopy() is commented out, but it's just something I tried that didn't work.

For testing, the values I've entered for array1 are 1, 2, 3, 4, 5.

#include <iostream>
#include <iomanip>
#include <array>

const int ARRAYSIZE = 5;

void ArrayCopy(std::array<int, ARRAYSIZE>, std::array<int, ARRAYSIZE>);

int main() {

    std::array<int, ARRAYSIZE> array1;
    std::array<int, ARRAYSIZE> array2 = {};
    
    std::cout << "Please input " << ARRAYSIZE << " integers: ";

    // Get user input into array1

    for (int i = 0; i < ARRAYSIZE; i++) {

        std::cin >> array1[i];

        }

  // DO NOT CHANGE THIS CODE
    std::cout << "\n\nBefore copy, array 1 is: \n";
    PrintArray(array1);
    std::cout << "\nAnd array 2 is: \n";
    PrintArray(array2, ARRAYSIZE);

    ArrayCopy(array1, array2);

    std::cout << "\n\nAfter copy, array 1 is: \n";
    PrintArray(array1);
    std::cout << "\nAnd array 2 is: \n";
    PrintArray(array2, ARRAYSIZE);

   // END CODE THAT YOU SHOULD NOT CHANGE

}

void ArrayCopy(std::array<int, ARRAYSIZE> array1, std::array<int, ARRAYSIZE> array2) {

    for (size_t i = 0; i < array1.size(); i++) {

        int *holder1 = &array1[i];
        int *holder2 = &array2[i];

        array2[i] = *holder1;

        /*
        int* temp = holder2;

        holder2 = holder1;
        holder1 = temp;

        int holderInteger = *holder2;

        std::cout << holderInteger;

        array2[i] = holderInteger;
        */

    }

}

Solution

  • You need to pass arrays by reference as for example

    void ArrayCopy( const std::array<int, ARRAYSIZE> &array1, std::array<int, ARRAYSIZE> &array2) {
    
        for (size_t i = 0; i < array1.size(); i++) {
    
            const int *holder1 = &array1[i];
            int *holder2 = &array2[i];
    
            *holder2 = *holder1;
        }
    }
    

    Otherwise the function deals with copies of the original arrays.

    Pay attention to that you could just assign one array to another like

    array2 = array1;
    

    For example

    void ArrayCopy( const std::array<int, ARRAYSIZE> &array1, std::array<int, ARRAYSIZE> &array2) {
        array2 = array1;
    }