how do you dynamically allocate multidimensional arrays?

Donn Seeley donn at utah-gr.UUCP
Tue Apr 30 10:51:30 AEST 1985

	From: geoff at burl.UUCP (geoff)

	I am trying to allocate a dynamic two-dimensional array of
	structures. ...

(Did you figure this out?  I noticed some cancel messages lying around
that looked like they might have been intended to nab your article...
In the event you were serious about posting this, and in consideration
that this might conceivably be of general interest, I'll answer your
question anyway...)

The problem is that you aren't dereferencing your pointer properly.
The pointer is declared correctly:

	struct fred (*p)[2][2];

But for some reason you didn't use it the way it was declared:

	p[1][1]->j = 10000;

We can rewrite this in a trivial way so that we can see what's wrong:

	p[1][1][0].j = 10000;

What this actually does is select the NEXT two-dimensional array after
the one to which 'p' points, extract element <1,0> from it and assign
10000 to its member, 'j'.

The rule of thumb that was overlooked here is that the declaration of a
C object parallels its use; thus the proper way to write what you want is:

	(*p)[1][1].j = 10000;

Hope this helps,

Donn Seeley    University of Utah CS Dept    donn at
40 46' 6"N 111 50' 34"W    (801) 581-5668    decvax!utah-cs!donn

More information about the Comp.lang.c mailing list