develooper Front page | perl.perl6.internals | Postings from July 2002

Re: multidimensional array

Thread Previous | Thread Next
Nicholas Clark
July 2, 2002 13:48
Re: multidimensional array
Message ID:
On Thu, Jun 27, 2002 at 05:42:10PM +0200, Josef Höök wrote:
> I've been thinking abit on howto implement multidimensional arrays and
> i found that its quite tricky :). I'm currently thinking of having
> a structure that contains a data pointer and its location in every
> dimension something like this:
> typedef struct CELL {
>   int dim[100];
>   int *data;
> } cell;
> cell *a = (cell *)malloc((unsigned) (2)*sizeof(cell *));
> // A cell with location in a 3 dim space a(2;4;6)
>  a->dim[0] = 2;
>  a->dim[1] = 4;
>  a->dim[2] = 6;
>  a->data = data1; 

I wouldn't like to do it quite like that, as you've got a hard coded constant
in there. Why should we prevent crazy people making arrays with dimensions
greater than 100, and why should we have most people who only want a 2D array
having to carry 98 unused ints around as baggage.

Also, your structure doesn't store how many dimensions the array is, so either
one has to pass the value (such as 3 in your example) around with it, or have
a->dim[3]=0 as an end of dim marker.

I'd be tempted to have a structure something like this:

typedef struct CELL {
  int num_dims;
  int *dim;
  int smalldim[3];
  int *data;
} cell;

where num_dims has the number of dimensions, and *dim is either a pointer to
a dynamically allocated array of dimensions, or a pointer to smalldim.
smalldim is used to store dimensions if your array is 3 or less, to save an
extra bit of allocation, which may well not sufficiently near to be in the CPU
cache. I'm assuming that most arrays will be less than 3 - obviously 3 can
be changed, probably as compile time option, based on tuning.

I'm not sure if having smalldim would be that much a win, and how the garbage
collector would like the idea of having to do something like

if (this->dim != &(this->smalldim))
  free (this->dim);

when freeing a struct CELL;

On Tue, Jul 02, 2002 at 03:24:03PM -0500, Dan Sugalski wrote:
> One of the nice things about PMCs is that all the implementation 
> details are just that--details. They hide on the other side of the 
> wall marked "Do Not Peek Past This Point". :)

or "Here Be Dragons"

> I really need a room with a wraparound whiteboard...

Does it really matter what shape the room is, once one has had the caps off
the marker pens for long enough? :-)

Nicholas Clark
Even better than the real thing:

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About