Mail Archives: djgpp/1999/06/21/06:42:06
In article <LOBBKLEPLBKLOKFELHOIAELLCCAA DOT djgpp AT niemeyer DOT net> you wrote:
> I'm still look for a way to allocate arrays with 2
> or more indexes.
The basic trick is that there is no such thing as a multi-dimensional
array in C. There are only one-dimensional arrays, but you can have an
array of arrays, as a replacement of multidimensional arrays.
Now, if you want the array to be dynamic (i.e. you can choose the size
of all the dimensions at run-time of the program), you're not really
talking about arrays, any more. It's *pointers*, now. Pointers can
also be accessed using the traditional array notation a[i]. Pointers
to pointers can thus be accessed by a[i][j], too. That's what the
first poster suggested, effectively:
char **store = malloc(height * sizeof(char *));
for (i=0; i<height; i++)
store[i] = malloc(width * sizeof(char));
This method will allow you to access store[i][j], just like you
normally would.
The other method is to forget about writing a[i][j], and use a single,
large block of memory, and compute the index manually, given 'i' and
'j':
char *store = malloc(width*height* sizeof(char));
Now, instead of store[i][j], you'ld have to write store[i*height+j].
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -