2D arrays

Requests for features
Post Reply
ShaunB
Member
Posts: 41
Joined: Mon Jan 02, 2012 6:13 pm

2D arrays

Post by ShaunB »

Hi,

Is it possible for a future revision of z88dk to support 2D arrays please?

Otherwise, do you have an example of a work around?

I want something like this:

Code: Select all

unsigned char starField[12][64];
Regards.

Shaun
alvin
Well known member
Posts: 1872
Joined: Mon Jul 16, 2007 7:39 pm

Post by alvin »

I think it's supported now although I don't know if dom is finished with it yet.

zsdcc supports multi-dimensional arrays.
sccz80 seems to be support it now.

The workaround for multi-dimensional arrays is to simply declare a one-dimensional array with enough elements and then when indexing, you compute the position inside the 1D array manually. This is what the compiler must do for multi-dimensional arrays but the computation is automatic.

Code: Select all

unsigned char starField[12][64];
starField[i][j] = 10;
becomes

Code: Select all

unsigned char starField[12*64];
starField[i*64+j]=10;
Jagged arrays are another method and can be faster that multi-dimensional array access because they do away with the runtime calculation "i*64" in the example above. What you make is an array of pointers to 1D arrays so that the first index i returns a pointer to an array of j elements. One disadvantage is that it occupies an extra max_i*2 bytes of memory for the pointers while another advantage (besides speed) is that the array indexing is the same as for the multi-dimensional case.

Code: Select all

//unsigned char starField[12][64];

unsigned char _starField[12*64];

unsigned char *starField[12] = {
        &_starField[0],   // every 64 elements
        &_starField[64],
        &_starField[128],
        &_starField[192],
        &_starField[256],
        &_starField[320],
        &_starField[384],
        &_starField[448],
        &_starField[512],
        &_starField[576],
        &_starField[640],
        &_starField[704],
};

void main(void)
{
        unsigned char i,j;
        
        starField[2][20] = 10;
        
        for (i=0; i!=12; ++i)
                for (j=0; j!=64; ++j)
                        starField[i][j] = 12;
}
sccz80 does not like this code so I'm going to create an issue for it now.
alvin
Well known member
Posts: 1872
Joined: Mon Jul 16, 2007 7:39 pm

Post by alvin »

Post Reply