Home » Various » Multidimensional Arrays without Subscript Operator

Multidimensional Arrays without Subscript Operator

Some time ago friend of mine asked me how to operate on array without subscript operator, and – to be honest – I supposed it’ll took less than few hours…

NOTE as for all pointer arithmetic it’s rather inadvisable to use this trick in ‘common life projects’.
But I have some more knowledge so I’m sharing! (:
And if you want something more about pointer arithmetic you can check my previous article.

Answer:
If you want to operate on table without using subscript operator you need to use this little instruction:

 * ( (e2) + (e1) )

It’ll work as long as one of arguments is pointer to table and second is integer value (within array range).

So if we, for example, have array tmp with five elements and we want to fill it with numbers from 1 do 5 we can write:

for(int i=0; i<5; ++i)
   *(tmp+i) = i+1;

And for multidimensional array answer is: It depends.
In my friend's case instead of:

 tmp[i][j]

I could use:

 * ( (j) + *( (i) + (tmp)) )

But it's valid only for array of pointers to arrays (eg. int ** pointers where we first point it to int*[] and then create new int[] in a loop), if you curious what you should use for 'conventional' twodimensional arrays check [2].

Wait, but Why?

Lets assume we have arr array.
As we all (probably) know the name of array is pointer to first element of that array, and contains address in memory where we can find it. By definition arr is &arr[0]. If we add 1 to arr in result we'll get address to next element of array, so:

 arr+i == &arr[i] 

And then we have tmp[ROWS][COLS] array. All we need to know is:

 tmp[i] == &tmp[i][0]

so if we add 1 to tmp[i] we'll get address of tmp[i][1]. As we already know

tmp[i] == *(arr+i)

therefore

 tmp[i][j] => *(tmp[i] + j) => *( *(tmp+i) +j ) 

Note: I found that for "conventional" arr[sizeX][sizeY] 2D arrays with int (*ptr)[sizeX] type formula for calculating cell address goes like that:
addr( arr) + (sizeof(type) * COLS * row + sizeof(type)*col);
Although I can't force it to work with my compiler with real 2D array (not 1D array like arr[sizeX * sizeY]);

Reference:
[1] Microsoft developer Network, Subscript Operator [], (accessed on 08.02.2015)
[2] Lin, Charles, Pointer arithmetics (accessed on 08.02.2015)

Posted in Various and tagged as ,

Comments are closed.