Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating 2d array from 1d arrays

if i have several arrays of the same datatype, what is the best way to copy them all into a 2d array. for example

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

int array2d[][];
//pseudo code array2d = array1 + array2

so that

array2d[0][0]; //=1 (first member of array1)
array2d[1][0]; //=9 (first member of array2)

considering an array is just a pointer to the first element, i thought I could do this, but it creates a compiler error.

array2d[0][0] = array1;
array2d[1][0] = array2;

I'm guessing I can't copy using references because an array needs its entries in contiguous memory? is there a memset like funciton I can use?

like image 733
cool mr croc Avatar asked Aug 22 '26 18:08

cool mr croc


1 Answers

Impossible. You need to copy element by element from one array to another.

Also you can mimic 2d array with array of pointers to arrays of ints.

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

int *array2d[2]; 

array2d[0] = array1;
array2d[1] = array2;

or this

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

int *array2d[] = {array1, array2}; 

cout << "[0][0]=" << array2d[0][0] << endl;
cout << "[1][0]=" << array2d[1][0] << endl;

OR REVERSE

If your goal is to present 2d array to some API, then you should refactor your side. For example, you can mimic your 1d arrays with pointers:

// an ampty array
int array2d[2][10];

// pointers to parts
int *array1 = array2d[0];
int *array2 = array2d[1];

int n;

// fill "arrays"
for(int i=0, n=1; i<10; ++i, ++n) {
    array1[i] = n;
}
for(int i=0, n=9; i<10; ++i, --n) {
    array2[i] = n;
}

// now you are ready
cout << "[0][0]=" << array2d[0][0] << endl;
cout << "[1][0]=" << array2d[1][0] << endl;
like image 196
Dims Avatar answered Aug 25 '26 09:08

Dims



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!