[A89] Re: Multi-dimensional Arrays in C...
[Prev][Next][Index][Thread]
[A89] Re: Multi-dimensional Arrays in C...
>Any suggestions?
I've attached a sample program demonstrating dynamic multi-dimensional
array allocation (works fine w/ gcc.) The best way to tackle the situation
is to remember that the concept of "multi-dimensional" arrays is an
abstraction and you can see the mechanics behind it by taking a close look
at what they really are, arrays of pointers.
The way I demonstrate isn't nice and magical, but I'm sure you could write
a function (perhaps using recursion) to dynamically create arrays of any
number of dimensions. MultiDimensionalAlloc() or something like that ;)
-- Attached file included as plaintext by Listar --
#include <stdio.h>
#include <stdlib.h>
int **array;
int main()
{
int i;
/*
* Allocate 256 elements of "int *". So, array[] is an array of 256 int *
* pointers.
*/
array = calloc(256, sizeof(int *));
/*
* Next, allocate memory using each of the 256 int * pointers. I'm only
* going to allocate one int of space per pointer for this example.
*/
for (i = 0; i < 256; i++)
{
array[i] = calloc(1, sizeof(int));
*array[i] = i;
}
/*
* In the last for-loop, you will notice that I assigned the current loop
* counter value to the memory allocated. This next for-loop prints out
* the values.
*/
for (i = 0; i < 256; i++)
printf("%d\n", *array[i]);
/*
* Free the memory.
*/
for (i = 0; i < 256; i++)
free(array[i]);
free(array);
return 0;
}
-- Attached file included as plaintext by Listar --
Bart
References: