copying an array into another

Oct 8, 2016 at 9:09am
closed account (G1vDizwU)
Hi guys,

Consider we have an array like this:

int ar1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

We want to initialize a second one, ar2, as a copy of ar1:

int ar2[10];

How many ways are there for doing it please?
Last edited on Oct 8, 2016 at 9:09am
Oct 8, 2016 at 10:05am
closed account (LA48b7Xj)
Here are 3 ways to do it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <algorithm>
#include <iostream>

using namespace std;

void f1()
{
    int ar1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int ar2[10];

    copy(begin(ar1), end(ar1), begin(ar2));

    for(auto e : ar2)
        cout << e << ' ';
    cout << '\n';
}

void f2()
{
    int ar1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int ar2[10];

    for(int i=0; i<10; ++i)
        ar2[i] = ar1[i];

    for(auto e : ar2)
        cout << e << ' ';
    cout << '\n';
}

void f3()
{
    int ar1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int ar2[10];

    int* p = ar1;
    int* q = ar2;

    while(p != ar1 + 10)
        *q++ = *p++;

    for(auto e : ar2)
        cout << e << ' ';
    cout << '\n';
}

int main()
{
    f1();
    f2();
    f3();
}
Last edited on Oct 9, 2016 at 6:27pm
Oct 8, 2016 at 2:56pm
closed account (G1vDizwU)
Thank you for your reply.
Oct 8, 2016 at 9:56pm
It's maybe worth mentioning that
ar2 = ar1
Doesn't copy the array.
Last edited on Oct 8, 2016 at 9:56pm
Oct 9, 2016 at 1:00pm
closed account (G1vDizwU)
Thanks mbozzi. Good point, yeah. :)
Oct 9, 2016 at 9:27pm
closed account (iN6fizwU)
mbozzi is correct that
ar2 = ar1
doesn't copy elements if ar1 and ar2 are int arrays.

Being slightly pedantic, perhaps, it would copy array elements if ar1 and ar2 were declared as
valarray <int>
which, incidentally, makes valarrays behave like standard Fortran 90/95 arrays. Heresy to talk about Fortran on a C++ forum, I guess.

Topic archived. No new replies allowed.