Path: utzoo!attcan!uunet!husc6!mailrus!cornell!uw-beaver!tikal!phred!daveh From: daveh@phred.UUCP (Dave Hampton) Newsgroups: comp.lang.c Subject: Re: "Dynamic Allocation of 2-D Arrays" Message-ID: <2347@phred.UUCP> Date: 14 Sep 88 15:36:31 GMT Reply-To: daveh@phred.UUCP (Dave Hampton) Organization: <355@quintus.UUCP>o Lines: 70 Thanks to all who replied to my query on the best way to dynamically allocate multi-dimensional arrays. Karl's note incorporated all of the other suggesttions which I received, so I am posting it (with permission) as a summary of the techniques required. ------------------------------------------------------------------------ >The closest that I have been able to come (for a 100 by 100 square array >of integers) is: > int (* array_name)[100]; > array_name = (int *) calloc (1000, sizeof(int)); > for (x=0; x free (array_name); First, a 100x100 array has 10000 elements, not 1000. Now, assuming that the column dimension is a constant expression, you're almost right. The type of an object looks just like the declaration with the name removed, so the type of `array_name' is `int (*)[100]'. The type `array of 100 ints' is denoted `int [100]'. What you want is: array_name = (int (*)[100])calloc(100, sizeof(int [100])); This could also be done with array_name = (int (*)[100])calloc(10000, sizeof(int)); but I think the former is clearer. If the column dimension isn't constant, you can't do this. You could instead use a pointer to a pointer rather than a pointer to an array (and despite what anyone tells you, pointers and arrays are not the same thing in C). This requires a bit more work to build and destroy, but can still be accessed using normal subscript notation: int **array_name; array_name = (int **)calloc(nrows, sizeof(int *)); for (x=0; x