C++ 2D array to 1D array

You are right with your supposition:

The cycle should be like:

for (q = 0; q < n; q++)
{
    for (t = 0; t < m; t++)
    {
        b[q * m + t] = a[q][t];
    }
}

It is always easier to consider such conversions from the view point of the higher dimension array. Furthermore with your code you did not actually modify i or j in the b assigning cycle, so you should not expect different values to be assigned to the different array members of b.


http://www.cplusplus.com/doc/tutorial/arrays/

In that link look at the section on pseudo-multidimensional arrays.

I've seen many examples that that get the subscripting algorithm wrong. If in doubt, trace it out. The order of sub-scripting a 2D array should go sequentially from 0-(HEIGHT*WIDTH-1)

#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT * WIDTH];
int n,m;

int main ()
{
  for (n=0; n<HEIGHT; n++)
    for (m=0; m<WIDTH; m++)
    {
      jimmy[n*WIDTH+m]=(n+1)*(m+1);
    }
}

First of all, the size of the 1D array should be n*m.

The cycle can be as follows-

int lim = n*m;

for(q = 0; q<lim; ++q) {

    b[q] = a[q/m][q%m];
}