|
Tiny Tutorial on Multidimentional Arrays
By: Aikito
Ever wanted to hold data in a table-like way? Well, now you can! It's easy with the super-duper multidimensional array! Anyway, let's start with an example of setting up a 2-dimensional array:
#define XSIZE 10 // number of columns
#define YSIZE 10 // number of rows
#define SIZE 100 // xsize*ysize
// a 2d array
int array[SIZE];
// returns a value from the 2d array
int GetVal(int x, int y) { return array[y*XSIZE+x]; }
// sets a value in the 2d array
void SetVal(int x, int y, int value) { array[y*XSIZE+x] = value; }
What we've done here is set up the variable to hold our data and the functions neccesary to access that variable in a meaningful way.
First off, we make some #defines. While this isn't absolutely neccesary, it helps if you want to change the size of the array quickly. As you can see, we've defined the X size, the Y size and the total size of the 1d array we want to use to emulate a 2d array.
Next, we allocate the actual memory via array[SIZE]. It's really a shame that we can't declare dynamic arrays because then we could just put array[XSIZE * YSIZE] (*psst* tSB!). Note: you can make your array of any type you wish -- string, int, whatever...
Finally, we set up what are known as accesor functions. These should be the only ways you ever manipulate your array. GetVal() extracts data from the specified place in the array and SetVal() puts data into the specified place in the array.
Well, that's practically it. Here are accessor functions for a 4d array as well if you're feeling daring:
int GetVal(int x, int y, int z, int w) { return array[(w*xsize*ysize*zsize)+(z*ysize*xsize)+(y*xsize)+x]; }
void SetVal(int x, int y, int z, int w, int value) { array[(w*xsize*ysize*zsize)+(z*ysize*xsize)+(y*xsize)+x] = value; }
Also, don't forget to make your array 4d as well:
#define XSIZE 10
#define YSIZE 10
#define ZSIZE 10
#define WSIZE 10
#define SIZE 10000 // xsize*ysize*zsize*wsize; rather large, if you ask me
// a 4d array
int array[SIZE];
Well, that concludes my first tutorial.
|