Path: utzoo!attcan!uunet!midway!uwvax!uwm.edu!rpi!zaphod.mps.ohio-state.edu!samsung!munnari.oz.au!metro!pta!yarra!melba.bby.oz.au!leo!zvs From: zvs@bby.oz.au (Zev Sero) Newsgroups: comp.lang.c Subject: Re: 2D array question Message-ID: <1990Jul3.025859.4690@melba.bby.oz.au> Date: 3 Jul 90 02:58:59 GMT References: <3336.268f44b2@cc.nu.oz.au> Sender: news@melba.bby.oz.au Organization: Burdett, Buckeridge and Young Ltd. Lines: 40 In-Reply-To: v8902477@cc.nu.oz.au's message of 2 Jul 90 02:57:22 GMT In article <3336.268f44b2@cc.nu.oz.au> v8902477@cc.nu.oz.au writes: struct a { int a1, a2, a3; }; array = (struct a *) calloc(xdim*ydim, sizeof(struct a)); and then *((array+x+y*ydim).a1) = value; which doesn't work. The following: (*(array + x + y * ydim)).a1 = value; or (array + x + y * ydim)->a1 = value; will work. Adding to a pointer still yields a pointer. However, try the following instead: array = (struct a **) malloc (ydim * sizeof (struct a *); for (i = 0; i < ydim; i++) array[i] = (struct a *) calloc (xdim, sizeof (struct a)); ... array[y][x].a1 = value; This will give you the almost-equivalent of declaring struct a array[ydim][xdim]; which you would have done if ydim and xdim were constants. The differences between the pointer and a proper 2d array are that the pointer is modifiable, and that if you free the pointer you should first free each element. Also, the elements of an array occupy a contiguous area of memory, and the elements of this pseudo-array might not, but I don't see what difference that makes. -- Zev Sero - zvs@bby.oz.au ...but we've proved it again and again that if once you have paid him the danegeld, you never get rid of the Dane. - Rudyard Kipling