Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!decwrl!uunet!mcsun!ukc!stl!stc!rmj From: rmj@tcom.stc.co.uk (Rhodri James) Newsgroups: comp.lang.c Subject: Re: ** help... Message-ID: <1884@jura.tcom.stc.co.uk> Date: 21 Aug 90 14:35:33 GMT References: <2409@dsacg2.dsac.dla.mil> Reply-To: rmj@htc2.UUCP (Rhodri James) Organization: STC Telecomms, Harlow Technical Centre, Harlow Lines: 58 In article <2409@dsacg2.dsac.dla.mil> nol2321@dsacg2.dsac.dla.mil (Jim Dunn) writes: >Why can't I do the following?!? (C'mon you gurus...) > >typedef struct _window { > int x; > int y; > int **array; [etc] >} WINDOW; > >main() >{ > int x, xL = 10; > WINDOW *w1; > > w1 = (WINDOW *) malloc(sizeof(WINDOW)); > >/* the problem is next */ > w1->array = malloc( xL * sizeof(int) ); You want the whole list or just the short version? :-) 1) array is an int ** so the malloc should be cast to that 2) the "elements" are int *, so that should be what you take sizeof. Pointers haven't been equivalent to ints for some while. 3) this isn't vastly relevant to PC applications, but doing a multiplication as your argument to malloc is just asking for alignment trouble. Either calloc(xL, sizeof(int *)), or (more grungily) malloc(sizeof(int *[xL])) (will this work if xL is a variable?) 4) you really ought to consider #defining xL rather than making it a variable. Unless you have pressing reasons otherwise. >/* isn't the above line legal, or how can I allocate mem for the storage */ It's legal, but hardly sensible. Actually, it isn't all that legal. > for(x=0;x < xL; x++) > w1->array[x] = (int *) malloc( 10 * sizeof(int *) ); This time you should be taking the sizeof an int! Comments above about multiplicative mallocs apply, and this time malloc( sizeof(int[10])) does work (I think). >} > >Jim >jdunn@dsac.dla.mil Hope this helps. Rhodri -- * Windsinger * "Nothing is forgotten..." * rmj@islay.tcom.stc.co.uk * Mike Whitaker * or (occasionally) * "...except sometimes the words" * rmj10@phx.cam.ac.uk * Phil Allcock