Matt
Matt

Reputation: 3852

std::copy two dimensional array

Hello I'm trying to use the std::copy() function to copy a two dimensional array. I was wondering if it's possible to do it like so! I keep getting a "Segmentation Fault" but the array is copied correctly. I've tried subtracting a few and adding a few to the end case for the copy function, but with no success.

    const int rows = 3;
    const int columns = 3;
    int myint[rows][columns]={{1,2,3},{4,5,6},{7,8,9}};
    int favint[rows][columns];
    std::copy(myint, myint+rows*columns,favint);

It's obvious that "myint+rows*columns" is incorrect, and it turns out that this value corresponds to entire rows such that "myint+rows*columns=1" means it will copy the entire first row. if "myint+rows*columns=2" it copies the first two rows etc. Can someone explain the operation of this for me?

Upvotes: 14

Views: 39896

Answers (1)

lulyon
lulyon

Reputation: 7225

std::copy(myint, myint+rows*columns,favint);

should be:

std::copy(&myint[0][0], &myint[0][0]+rows*columns,&favint[0][0]);

prototype of std::copy:

template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );

Notice that pointer to array element could be wrapper as an iterator.

Upvotes: 33

Related Questions