[LCP]2D arrays:dynamic allocation and freeing
Steve Baker
ice at mama.indstate.edu
Wed Feb 2 23:36:01 UTC 2005
This treatise on 2D arrays brought to you by Extreme Boredom(tm).
Pankaj Gode <godepankaj at yahoo.com> wrote:
> The way to dynamically allocate a 2D array is :
>
> int a(*)[5];
>
> a=(int (*)[5])malloc(sizeof(int)*5);
>
>
> This will create array of pointer to arrays.
In what language? To dynamically allocate a 2 dimensional array in C, you
would do:
int **a, i;
a = malloc(sizeof(int *) * 5);
for(i=0;i<5;i++) a[i] = malloc(sizeof(int) * 5);
The first malloc allocates an array of pointers, then the loop allocates an
array of data for each row. Then you can use a[i][j] to access an element.
Alternatively you could do something like:
int *a;
a = malloc(sizeof(int) * (N*M));
And use *(a+(i*N)+j) or a[(i*N)+j] to access an element, which is close to
how C does things when you allocate a 2D array on the stack. This has the
benefit of being slightly faster overall (debatable, and implementation
specific), easier to malloc, free and initialize the array, but ugly to
implement (although some #defines can clean things up, I do not recommend
using #defines extensively.)
For completness I might also mention you could do something like:
int **a, i;
a = malloc(sizeof(int *) * N);
a[0] = malloc(sizeof(int) * (N*M));
for (i=1;i<N;i++) a[i] = a[0]+(i*M);
Then you could access it with a[i][j] and init the array easily with memset
or somesuch and free with just two free statements: free(a[0]); free(a);
> Is my way of freeing ok
>
> for(i=0;i<5;i++)
> free(a[i]);
>
> Because it will free the pointers , what about the elements associated with
> those pointers.
It should be followed with a free(a), to free the array of pointers.
- Steve
More information about the linuxCprogramming
mailing list