Multi-dimensional array using dynamic memory allocation

Quote:

> Hello guys,

> I would like to declare a multi-dimensional array using dynamic memory

> allocation. While I have the code for one dimension,

> int x_length=5;

> int *one_dimension_array;

> int (int *)malloc(x_length*sizeof(int));

> /* test */

> one_dimension_array[2]=3453;

> I just can't work out how to add the second dimension so I can write

> something like

> two_dimensions_array[2][3]=3453;

In C99, you can simply do this:

int y_length=6, x_length=5;

int two_dimension_array[y_length][x_length];

two_dimension_array[3][2] = 3453;

thus avoiding the need for malloc. If you still want to use malloc

(presumably because you need a longer lifetime for the array), you could do:

int y_length=6, x_length=5;

int (*two_dimension_array)[x_length];

two_dimension_array = malloc(y_length * x_length * sizeof(int));

two_dimension_array[3][2] = 3453;

In C90, you're limited by the fact that all array dimensions other than the

first must be constants, so you can only do:

int y_length=6;

#define X_LENGTH 5

int (*two_dimension_array)[X_LENGTH];

two_dimension_array = malloc(y_length * X_LENGTH * sizeof(int));

two_dimension_array[3][2] = 3453;

This is somewhat annoying, but prevented the need for the compiler to create

"hidden" variables storing the dimensions of array types. The standard work

around is to do the subscripting manually:

int y_length=6, x_length=5;

int *two_dimension_array;

two_dimension_array = malloc(y_length * x_length * sizeof(int));

two_dimension_array[3*x_length + 2] = 3453;

--

Kevin Bracey

http://www.bracey-griffith.freeserve.co.uk/

--