BruceS
7/28/2011 3:02:00 PM
On Wed, 13 Jul 2011 18:50:01 +0000, Seebs wrote:
> So, for a really long time, I've done this:
>
> int **allocate_multidim_array(int n, int m) {
> int **a;
> int i;
>
> a = malloc(n * sizeof(int *));
> for (i = 0; i < n; ++i) {
> a[i] = malloc(m * sizeof(int));
> }
> }
>
> void free_multidim_array(int **a, int n) {
> int i;
> for (i = 0; i < n; ++i)
> free(a[i]);
> free(a);
> }
>
> (Not really as functions, normally, just presenting them this way so you
> can see the logic clearly.)
>
> Recently, I had cause to do this, and it occurred to me I could do
> something else:
>
> int **allocate_multidim_array(int n, int m) {
> int **a;
> int *data;
> int i;
>
> a = malloc(n * sizeof(int *));
> data = malloc(n * m * sizeof(int));
> for (i = 0; i < n; ++i) {
> a[i] = data + (i * m);
> }
> }
>
> void free_multidim_array(int **a, int n) {
> free(a[0]);
> free(a);
> }
>
> So far as I can tell, this is just plain cleaner, simpler, and so on.
>
> Am I missing something? Is the former idiom actually widespread, or did
> I just invent it wrong? Is there a benefit to it I haven't considered,
> other than sparse arrays or things larger than you can allocate as a
> single object?
>
> -s
I've just been catching up, doing my usual looking for certain posters,
when I came across this. Can it be that I'm the only one who noticed the
missing returns? I know it's inconsequential, as Seebs said he isn't
really using functions, but still...