Mail Archives: djgpp/1998/02/10/14:08:34
In article <34DF9744 DOT C7CFDBFE AT ea DOT oac DOT uci DOT edu> you wrote:
> Can someone explain to me how to dynamically declare a 2-d array?
[Yes, this is slightly off-topic, but as the thread has already
started to grow, I'll just add my DM 0,02]
In addition to the explanations given by others, let me describe a
method that allows both kinds of access: explicit computation of an
address and the [][] notation. Let's allocate a dynamical 'char
a[n][m];':
char *a_inner = malloc(n*m*sizeof(char));
char ** a = malloc(n*sizeof(char *));
int i;
for (i=0; i<n; i++)
a[i] = a_inner + i*m;
This sets up a large, *contiguous* array a_inner, and a set of
pointers into that array. To access Element a[k][j], you can do any of
the following, whichever seems fit for the situation at hand:
a[0][k*m+j];
a_inner[k*m+j];
a[k][j];
(BTW: I first learned about this from the comp.lang.c FAQ. If you don't
have that, go get it. It's about the most valuable source of information
you'll ever get about C in general, only second to the original work
itself: K&R2)
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -