0

I have one-dimensional array

int* a = new int[n * m];

and i need to treat it as two-dimensional i.e

a[i][j] = a[n * i + j]

I have tried playing around using directives and googled a lot. But nothing worked for me.
Is there any way to do so? Smt. like define a[i][j] a[n * i + j] ?
Thanks.

T_Igor
  • 53
  • 3

2 Answers2

2

You need to define a second array that contains pointers. Something like this:

int **b=new int *[m];

for (int i=0; i<m; ++i)
     b[i]=&a[i*n];

After that, b[i][j] will refer to a[n*i+j].

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • While this is a possible solution, it does have some problems that a single "array" doesn't, mainly about locality and CPU caching. – Some programmer dude May 16 '16 at 12:43
  • I don't want to allocate array of pointers and then each allocate memory for each of the pointer. I just want substitution `a[i][j] = a[n * i + j]` – T_Igor May 16 '16 at 12:51
  • @T_Igor Note that the code in the answer doesn't actually do what you think it does. The loop doesn't allocate memory, just assignment. – Some programmer dude May 16 '16 at 12:55
1

Since you're programming in C++ you could create a wrapper-class which holds the array, and have an operator[] function which returns a proxy object whose operator[] function performs the n * i + j calculation and returns a reference to the wanted element.

Alternatively you can create an inline function or function-like macro which takes the array and indexes as arguments and return the element.

But without hacks like the one in Sams answer of wrapper classes, there is no way of getting a "true" array of arrays like you want.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621