A pointer to a 3-D array, or an array of ptrs to 2-D arrays?

Joseph N. Hall jnh at ecemwl.ncsu.edu
Thu Nov 16 02:52:59 AEST 1989


As an aside, I've found it useful to dynamically allocate matrices like
this (hastily paraphrased, it might have a typo or two in it):

	double **NewDoublem(int isize, int jsize)
	{
		int i;
		double **doublem, *doublev;

		doublem = (double **) malloc(sizeof(double *) * isize);
		doublev = (double *) malloc(sizeof(double) * isize * jsize);

		for (i = 0; i < isize; i++) {
			doublem[i] = doublev + i * jsize;
		}

		return doublem;
	}

This has the advantage over the more frequently-seen approach (allocate a
separate vector for each row) that you can free such a "matrix" without
knowing its size:

	free((void *) *doublem);
	free((void *) doublem);

...and, of course, you make fewer calls to malloc.

Hope this is a useful and not tiresomely obvious suggestion for some of you.



v   v sssss|| joseph hall                      || 4116 Brewster Drive
 v v s   s || jnh at ecemwl.ncsu.edu (Internet)   || Raleigh, NC  27606
  v   sss  || SP Software/CAD Tool Developer, Mac Hacker and Keyboardist
-----------|| Disclaimer: NCSU may not share my views, but is welcome to.



More information about the Comp.lang.c mailing list