Welcome, Guest. Please login or register.

Author Topic: Finding the address of an array element  (Read 8771 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show all replies
Re: Finding the address of an array element
« on: March 14, 2003, 06:33:14 AM »
The number of elements in such an array is simply
m1 x m2 x m3 x ... x mN

where any dimension has elements indexed 0 to m-1

A linear array is m1 elements,
A 2D array is m1 x m2
A 3D array is m1 x m2 x m3 etc.

The total size of memory to allocate is
number of elements x sizeof(element)

At this point, since you are doing the pointer math, you are free to arrange your data any way you wish, but probably the simplest way is to build it up a layer at a time.

Think of the number 9999 as a 4D array with m1,m2,m3 and m4 = 10 (elements 0-9) Then the simplest way to traverse all the elements is thus:
0000
0001
0002
0003 etc ...

0009
0010
0011
0012 etc ...

9998
9999

So, an element at n1,n2,n3,n4 is at

n1 + (n2 * m1) + (n3 * m1 * m2) + (n4*m1*m2*m3)

You can expand this to as many dimensions as you wish (and watch all your memory magically disappear  as the storage requirements rapidly approach huge :-D ).
 

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show all replies
Re: Finding the address of an array element
« Reply #1 on: March 15, 2003, 07:15:25 AM »
If you do this often, you may be doing too many multiplications. How about adding another array to keep track of the stride of each dimension, then calculate the values at the time of array creation.

i.e. you add
stride[0] = 1; // single element always is one wide!
for (i=1;i  stride = stride[i-1] * max_element_size[i-1];

// then go through again to mult in the sizeof()
for (i=1;i  stride *= type_size;

//Now you can find your address with
address = base;
for (i = 0; i  address += element_values * stride;

which will save on multiplies as the dimensions grow and ... should compile to better code on G4 with an Altivec aware compiler!!! :-)