Path: utzoo!censor!geac!torsqnt!hybrid!scifi!bywater!uunet!cai!davel From: davel@cai.uucp (David W. Lauderback) Newsgroups: comp.lang.c Subject: Re: How do I use Malloc to dynamically create a two dimensional array Message-ID: <1991Jan20.100940.16041@cai.uucp> Date: 20 Jan 91 10:09:40 GMT References: <7046@crash.cts.com> <20981.27984433@merrimack.edu> Reply-To: davel@cai.UUCP (David W. Lauderback) Organization: Century Analysis Incorporated Lines: 45 In article <20981.27984433@merrimack.edu> gelinasm@merrimack.edu (Mark Gelinas) writes: >In article <7046@crash.cts.com>, kevin@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.