populate two-dimensional array with two one-dimensional arrays

closed account (1Ck93TCk)
I'm having a hard time working out how to approach this, and I didn't find anything on web or forum searches that helped.

I have two one-dimensional arrays of size 20.
I have a two-dimensional array of 10 rows and 4 columns that gets populated by the two arrays. The part I'm stuck at is this - I'm supposed to populate the array such that the first array (alpha[20])is used for the first five rows, and the second array (beta[20]) is used for the last five rows.

I know how to use a for loop to populate an array, but I'm stuck on how to do this with two arrays, making sure the elements are in the correct location.

I'm hoping someone can give me a little guidance or point me in the right direction. Thank you for any help!
if your 2-d array is fixed on the stack, eg
int d2[10][4];
then you can flatten it.

int* d21d = &(d2[0][0]);
you can now memcpy the sources into d21d and it will land correctly and will be correct when you go into d2[][] !!!memcpy will not work for some things, I am assuming this is a simple array of integers. strings, vectors, things that have pointers inside them, memcpy = bad!!

if your 2-d array is pointer based (new[]) this won't work as the memory won't be a solid block. You can force this, however, by allocating a 1-d and then back-fitting it into a 2-d, which is very ugly.

you can just do 2 pairs of for loops to copy it all. for(0-9) for(0-3) dest[r][c] =source[index++]; style, one for each source.

the syntax for this stuff is annoying, so if you need to see something, Ill let you pick an option before trying to go deeper...
Last edited on
Crudely perhaps
1
2
3
4
5
6
7
8
9
10
11
12
int a = 0;
for ( int r = 0 ; r < 5 ; r++ ) {
    for ( int c = 0 ; c < 4 ; c++ ) {
        twod[r][c] = alpha[a++];
    }
}
int b = 0;
for ( int r = 5 ; r < 10 ; r++ ) {
    for ( int c = 0 ; c < 4 ; c++ ) {
        twod[r][c] = beta[b++];
    }
}


Eliminate the copy/paste by making a function.
closed account (1Ck93TCk)
I got it figured out. I just needed a nudge. Thank you!
Topic archived. No new replies allowed.