Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!snorkelwacker!bloom-beacon!daemon From: scs@adam.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: Answers to Frequently Asked Questions (FAQ) on comp.lang.c Summary: buglet in 2D array allocation examples Message-ID: <1990Aug2.221734.10191@athena.mit.edu> Date: 2 Aug 90 22:17:34 GMT Expires: 1 Aug 90 05:00:00 GMT References: <1990Aug1.042116.20244@athena.mit.edu> Sender: daemon@athena.mit.edu (Mr Background) Reply-To: scs@adam.mit.edu (Steve Summit) Organization: Thermal Technologies, Inc. Lines: 21 In article <1990Aug1.042116.20244@athena.mit.edu> I wrote: >A: It is usually best to allocate an array of pointers, and then > initialize each pointer to a dynamically-allocated "row." > > int **array = (int **)malloc(nrows * ncolumns * sizeof(int *)); > for(i = 0; i < nrows; i++) > array[i] = (int *)malloc(ncolumns * sizeof(int)); This code wastes space and is misleading. The initial "dope vector" need only contain a pointer for each row of the intended array, not each element: int **array = (int **)malloc(nrows * sizeof(int *)); The same problem afflicts the second posted 2D allocation example, as well. Thanks to Freek Wiedijk for pointing this out. Steve Summit scs@adam.mit.edu