there is a way to morph a block to look 2-d without the loop. hang on, Ill look it up.
I think this is one way, hopefully I did this right... and hopefully 'rows' isnt actually columns, Im having concentration issue today.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int main()
{
int * i = new int[100];
for(int x = 0; x < 100; x++)
i[x] = x;
typedef int rows[10]; //making a 10x10 here
rows* rp = (rows*)(i);
cout << rp[3][4] << endl; //3rd row, 4th colum... 34 (3*10+4)!
typedef int rows2[5]; //making a 5x20 here
rows2* rp2 = (rows2*)(i);
cout << rp2[3][4]; //3rd row, 4th colum... 19 (3*5+4)
}
|
I think you can do the above without the typedefs, using some other pointer & casting magic. The idea is the same, whatever syntax you need to get there
for any beginners, what this does conceptually is make a 1-d array of 1-d arrays, giving a 2-d array. More precisely, deep inside, you create a type that is N units wide, and take a pointer to that. C++'s strongly typed pointers allocate that width for you, so when you cast the big block to a pointer of the wide small type, it slices it for you, moving a full row at a time when you add 1 to that index, because +1 is N units wide.
these tricks can give you some really bad bugs if you mess it up. It yields high performance at high risk.