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)?

5
  • 1
    Consider this answer: stackoverflow.com/a/13937325/942596 , It shows how to use a 1D array as a 2D array. Commented Jan 29, 2013 at 18:33
  • @ahenderson: yes but is it a row-major order or column-major order there? cause I need both Commented Jan 29, 2013 at 18:37
  • 1
    The code is for Row-major layout. Commented Jan 29, 2013 at 18:44
  • @ahenderson: ok, thanks, so one less :D Maybe you know how to make a column-major order? Commented Jan 29, 2013 at 18:45
  • Can't you always get column-major from row_major by using the transpose. so, swap (column, row) values. Commented Jan 29, 2013 at 18:52

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

great, thank you. How about column-major, is it like this: oneD[1*H+2] == m[1][2]; ? – Brian Brown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.