Dynamic multidimensional arrays

Chris Torek chris at mimsy.UUCP
Fri Jun 17 00:26:41 AEST 1988


>>In article <4556 at haddock.ISC.COM> karl at haddock.ima.isc.com (Karl Heuer)
>>writes:
>>>If you allocate the entire array (including space for the pointers as well as
>>>the contents) in a single chunk, then you don't need all those free_array()
>>>routines -- the standard free() will work.  I've written it this way.

The problem with this is alignment.

	size_t i, n_rows, n_cols;
	void *p;
	void *malloc(size_t size);
	ty *data_area, **row_area;

	p = malloc(n_rows * sizeof(ty *) + n_rows * n_cols * sizeof (ty));
	if (p == NULL) ...
	row_area = p;
	data_area = (ty *)(row_area + n_rows);
	for (i = 0; i < n_rows; i++)
		row_area[i] = data_area + i * n_cols;

This allocates the row vectors and the array, and sets up the row
vectors to point to the rows.  But if `ty' is `double', there
is no guarantee that *data_area will not trap---for instance,
if n_rows is odd and sizeof(double *)==4 and sizeof(double)==8
and doubles must be aligned on an eight-byte boundary.

In article <8099 at brl-smoke.ARPA> gwyn at brl-smoke.ARPA (Doug Gwyn) writes:
>Karl's point is that the "row vector" can be contiguous with the MxN data
>area.  That is indeed a nice idea, and I think I'll change some of our
>applications to do this.

To do it you need to be able to align `data_area' above, which is
why we need some sort of standard <align.h> header.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list