0

Lets say, I have a MxN arrays: int *b; and int **c; where

  1. values in b are stored by columns (from c) and I need to put values from c to b
  2. values in b are stored by rows (from c) and I need to put values from c to b

I know that basicly I would do it like that:

j = index / N;
i = index - (j * M);

in order to convert a 1D index into a 2D co-ordinate but have a problem how to implement those 2 cases, 1) and 2)?

Brian Brown
  • 3,873
  • 16
  • 48
  • 79

1 Answers1

2

Let W be the width of the 2D array, and H its height. Then assuming row-major layout, the 1D index 'ix' relates to the 2D-index [x,y] as such:

ix = y*w + x;
y = ix / w;  // implicit floor
x = ix % w;

e.g.:

const int W = 3, H=2;
int m[H][W] = {{1,2,3}, {4,5,6}};
int* oneD = &m[0][0];
assert(oneD[1*W + 2] == m[1][2]); // element 6, y=1, x=2
emilk
  • 324
  • 2
  • 5