Answers to Frequently Asked Questions (FAQ) on comp.lang.c

Steve Summit scs at adam.mit.edu
Fri Aug 3 08:17:34 AEST 1990


In article <1990Aug1.042116.20244 at 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 at adam.mit.edu



More information about the Comp.lang.c mailing list