Groovy hepcat Ben C was jivin' on 13 Apr 2006 09:45:02 GMT in
comp.lang.c.
Re: Not fully comprehending arrays and dynamic memory.'s a cool scene!
Dig it!
On 2006-04-13, Mark Healey <di*@spammer.die> wrote: I'd like to allocate some memory for a two dimensional array.
The problem is that whenever I try to use pointer arithmetic I screw up.
I just want to use conventional array type statements to get at the memory.
Is there a way to do this?
It can be done, but it's a bit tricky, and even easier to screw up I
would say.
You can allocate one like this:
int (*d)[3][3] = malloc(sizeof *d);
And use it like this:
(*d)[2][1] = 100;
Or, even easier, like this:
#define ROWS 3
#define COLS 3
int (*d)[COLS] = malloc(ROWS * sizeof *d);
.... /* Checking for errors, etc. */
d[2][1] = 100;
Or, slightly trickier (because you have to handle multiple
allocations and deallocations), like so:
#define ROWS 3
#define COLS 3
int i;
int **d = malloc(ROWS * sizeof *d);
.... /* Checking for errors, etc. */
for(i = 0; i < ROWS; i++)
{
d[i] = malloc(COLS * sizeof *d[i]);
... /* Checking for errors, etc. */
}
d[2][1] = 100;
Or, even better still, simpler (because there are only two
allocations):
#define ROWS 3
#define COLS 3
int i;
int **d = malloc(ROWS * sizeof *d);
.... /* Checking for errors, etc. */
*d = malloc(ROWS * COLS * sizeof *d);
.... /* Checking for errors, etc. */
for(i = 1; i < ROWS; i++)
{
d[i] = d[i - 1] + COLS;
}
d[2][1] = 100;
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?