help needed about dynamic space allocation

Ken "Turk" Turkowski turk at apple.UUCP
Thu Nov 27 07:33:00 AEST 1986


>> fano at lifia.UUCP (Rampa*)
>> I need advice on dynamic space allocation for multidimensionnal arrays:
>>
>>   float **sig;                          /* matrix declaration     */
>>   sig = (int *)malloc(n * sizeof(int)); /* allocates space for sig */

There have been numerous responses to get the declarations consistent, so I
won't belabor them here.

However, I would like to point out the use of a function that can speed up the
program considerably when you are only allocating temporary variables.  The
function is alloca(), and allocates memory from the stack, rather than from
the heap.  The result is that allocation is simpler, and vanishes automatically
when you exit the routine.

The purpose of alloca() is to compensate for the deficiency in C that does not
allow you to do something like this:

	func(a, n)
	int *a, n;
	{
		int b[n+1];	/* <- C doesn't allow this */
		. . .
	}

by doing this:

	func(a, n)
	int *a, n;
	{
		int *b;
		b = (int *)(alloca((n+1) * sizeof(int)));
		. . .
-- 
Ken Turkowski @ Apple Computer, Inc., Cupertino, CA
UUCP: {sun,nsc}!apple!turk
CSNET: turk at Apple.CSNET
ARPA: turk%Apple at csnet-relay.ARPA



More information about the Comp.lang.c mailing list