How do I use Malloc to dynamically create a two dimensional array

David W. Lauderback davel at cai.uucp
Sun Jan 20 21:09:40 AEST 1991


In article <20981.27984433 at merrimack.edu> gelinasm at merrimack.edu (Mark Gelinas) writes:
>In article <7046 at crash.cts.com>, kevin at crash.cts.com (Kevin Hill) writes:
>>    I have a problem, and it may seem basic, but how do I use
>> malloc to create an array of type int i[100][100];
>>
>
>	Since 2-D arrays can exist as consecutive addresses in memory,
>(stored/read rowwise I believe), why not try something like
>
>	int **i;
>	int rowsize, colsize;
>	.
>	.
>	*i = (int *) malloc(sizeof(int)*rowsize*colsize);
>
>
>I have not tried this myself, but from what I can recall, it should work.
I have used this method.
>
>Corrections, questions, additional suggestions welcomed.
>
>Mark
>

While that will work on most (if not all compilers), I believe the "correct"
way to do this is as follows:

func()
{
	extern void	*malloc();   /* this sould be in a header not here */
	int	(*malloced)[100];    /* parentheses are important */
	/* you want a pointer to an array of a 100 int's */
	/* not a 100 int pointers */

	malloced = (int (*)[100]) malloc(sizeof(int [100][100]));
}
While the (type def) looks awful, what's (*).  If you remember this simple
rule, you will never have problems with type casts.  Take the variable's
declaration "int (*malloced)[100]", remove the variables name and surround
it with parentheses and you've got the typedef you want "(int (*)[100])".
-- 
David W. Lauderback (a.k.a. uunet!cai!davel)
Century Analysis Incorporated
Disclaimer: Any relationship between my opinions and my employer's
	    opinions is purely accidental.



More information about the Comp.lang.c mailing list