Welcome, Guest. Please login or register.

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

Description:

0 Members and 1 Guest are viewing this topic.

Offline jdiffend

  • Sr. Member
  • ****
  • Join Date: Apr 2002
  • Posts: 302
    • Show all replies
Re: Finding the address of an array element
« on: March 14, 2003, 05:53:26 PM »
Off the top of my head I'd say the only simple  :-?  way I can think of to do this is to write a recursive routine where it calls itself to calculate the previous dimension and bases it's calculation off of that which is based on the previous dimension and so on.  It will handle as many dimensions as your stack space will allow for the recursion.  This is also limited by the maximum value your pointer can handle.

You'd need the index within each dimension, the size of that dimension and the sizeof the object you are storing in that nth dimensional array.  They would need to be stored in an array, string, or whatever to be read by the recursive routine.  So, if you want a n dimensional array with each dimension having it's own size you would need an array kinda like this:
//n is number of dimensions
object_position[n] = {27, 2000, ... 100}; // where you have a position within each dimension
dimension_size[n] = {
  {size_n0},
  {size_n1},
  ...
  {size_nn}
}  // where you have the size of each dimension


The dimension size is the return value and the actual pointer is static so offsets are added to it as the calculation goes along.  You pass the recursive routine the the index into the dimension_size array which subtracts one and calls itself until it's zero.  Then calculations start and returns commence.

But that's just off the top of my head.  :-D
 

Offline jdiffend

  • Sr. Member
  • ****
  • Join Date: Apr 2002
  • Posts: 302
    • Show all replies
Re: Finding the address of an array element
« Reply #1 on: March 14, 2003, 05:55:57 PM »
 

Offline jdiffend

  • Sr. Member
  • ****
  • Join Date: Apr 2002
  • Posts: 302
    • Show all replies
Re: Finding the address of an array element
« Reply #2 on: March 14, 2003, 06:16:25 PM »
Oh, one more thing.  If you just set up the recursive routine to calculate the offset rather than an actual pointer you just use ArrayBaseAddress + (offset * sizeof(array_element)) to get the actual memory address.

This will actually be faster than doing the calculation in the recursive routine.

The recursive routine is basicly an n to 1 dimensional array index converter.

Hmmmm.... if you typecast it to a 1 dimensional array you could use something more like this to access it:
array1D[offset]
 

Offline jdiffend

  • Sr. Member
  • ****
  • Join Date: Apr 2002
  • Posts: 302
    • Show all replies
Re: Finding the address of an array element
« Reply #3 on: March 14, 2003, 10:17:19 PM »
Um... brain fart on my part... no recursion needed.  Just use nested loops.  DU-OH!
(recursion is slower than an iterative approach)

Glad I could help.