Copying the elements of a 2D Array to a 1D Array (C++)

Hello,
I am a new programmer. I am trying to copy the elements of this 20x3 array into a 1x60 or 60x1 array

an[60]=A[20][3]

one of my attempts is:
for (i=0;i<20;i++) {
for(j=0;j<3;j++){
at1[i]=A[i][j];
at2[i]=A[i][j];
at3[i]=A[i][j];}
}
an[60]={at1,at2,at3};
closed account (1yR4jE8b)
1
2
3
4
5
6
7
8
9
10
11
12
13
const int rowSize = 20;
const int colSize = 3;
int multiDim[rowSize][colSize];

int data[rowSize * colSize];

for(int row = 0; row < rowSize; ++row)
{
	for(int col=0; col < colSize; ++col)
	{
		data[row*colSize + col] = multiDim[row][col];
	}
}
closed account (1yR4jE8b)
Also, read this:

http://cplusplus.com/forum/articles/17108/

This is very important to understand. While it's important to understand how they work, and how to use them. Don't ever use them yourself :P
Thanks for your help!
In cases where the memory is contiguous, would it be possible to just use another pointer to access the elements?

For example:
1
2
3
4
5
6
7
8
9
int md[10][10] = { /* initialize elements */ };
int * p = &md[0][0];

for( int i = 0; i < 100; ++i )
{
    cout << *p++ << endl;
    // or even:
    cout << p[i] << endl;
}


EDIT: This worked on my machine using GCC. I'm not sure that all implementations would store the array data contiguously. This might not be portable.
Last edited on
closed account (1yR4jE8b)
I wouldn't bet on it. I'm not sure if it's dictated by the standard either, if it isn't, then you most definitely cant'.
moorecm is right provided it's a "straight" MD array (not nested new or anything like that).

You can also do this:

1
2
3
4
int md[10][10] = {...};

for(int i = 0; i <100; ++i)
  cout << md[0][i] << endl;


Even though i goes out of bounds of one of the dimensions, it's still in bounds on the whole array.

I'm 99.99% sure this is perfectly safe and reliable.
Topic archived. No new replies allowed.