[ back to toc ]

how to have variable rows in multidimensional array

Date: 2002/01/05 13:32

Q:
how to have variable rows in multidimensional array.
for eg
1) char array[var][constant]
2) char array[var][var]

A:
This is a typical question and the answer is not trivial.

First of all you can not do that.

On the second thought: you can do something that will fit your needs.

Lets say that you need a two dimensional array containing int elements.
You want the array ragged, which means that the different rows may have
different number of elements.

int **a;

is a pointer to an int* or to an array of int* values.

a = malloc( n * sizeof(int *));

now you already have an array of pointers (unitialized!).

for( i=0 ; i<n ; i++ ){
a[i] = malloc( k * sizeof(int));
}

here k can be any expression resulting the number of elements you want in
that row.

After that you can access the individual elements saying a[i][j]. That is
actually what you wanted.

On the other hand you have extra pointers occupiing memory. But that is
unavoidable.

You can do it similarly for more number of dimensions, and for other types
not being int.

Take care of the memory allocation and releases. And do not overindes the
arrays.

Regards,
Peter

[ back to toc ]