Assigning part of a 2d array to a new 2d array

I am trying to do this, but it is giving me "initializer fails to determine size of ‘b’"

int main()
{

int a[12][2];
a[0][0] = 1;
a[0][1] = 1;

int b[][2] = a[0];

return 0;
}
You cannot directly assign entire rows of arrays. You may use copy, see:

http://www.cplusplus.com/reference/algorithm/copy/?kw=copy

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{

int a[12][2];
a[0][0] = 1;
a[0][1] = 1;

int b[12][2];

std::copy(a[0], a[0] + 2, b[0]);

return 0;
} 
you can't do that in c++m you have to do it this way:
1
2
3
4
5
6
int b[12][2];
for( int i = 0; i < 12; i++ )
{
    b[ i ][ 0 ] = a[ 0 ];
    b[ i ][ 0 ] = a[ 1 ];
}
Last edited on
@coder777

your code is wrong, here is the correct version:
 
std::copy( a, a + 2, b );


and you have to #include <algorithm> to use std::copy
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
using namespace std;

int main()
{
   vector< vector<int> > a( 12, vector<int>( 2 ) );
   a[0][0] = 1;
   a[0][1] = 1;

   vector< vector<int> > b( 12, vector<int>( 2 ) );
   b[0] = a[0];

   for ( int i : a[0] ) cout << i << ' ';
   for ( int i : b[0] ) cout << i << ' ';
}
Alternatively (if I understand what you are trying to do):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>

struct Thing {
    int a, b;
};

std::ostream& operator<<(std::ostream& os, const Thing& th) {
    return os << th.a << ", " << th.b;
}

int main() {
    std::vector<Thing> stuff { {1, 1}, {1, 0}, {0, 1} };
    Thing thing { stuff[1] };
    std::cout << thing << '\n';
    thing = stuff[2];
    std::cout << thing << '\n';
}

fewdiefie wrote:
your code is wrong, here is the correct version:
So? And what is actually wrong with my code? It does what i intended: copy a row. Or in other words:

Assigning part of a 2d array to a new 2d array

While your code does not even compile. I suggest that you test the code before you judge it.

fewdiefie wrote:
and you have to #include <algorithm> to use std::copy
That's in the link.

@fewdiefie
You forgot that a is a 2D array, so a[0] is the address of a 1D row in that array.
Topic archived. No new replies allowed.