Foad S. Farimani
Foad S. Farimani

Reputation: 14016

How can I make multidimensional dynamically allocated arrays in C?

before you mark this as a duplicate please notice that I'm looking for a more general solution for arrays of arbitrary dimensions. I have read many posts here or in forums about making 2D or 3D arrays of integers but these are specific solutions for specific dimensions. I want a general solution for an array of any dimension. First I need to have a type of intlist as defined below:

typedef struct{
   int l // length of the list
   int * e // pointer to the first element of the array
}intlist;

this actually fills the gap in C for treating arrays just as pointers. using this type I can pass arrays to functions without worrying about loosing the size. then in the next step I want to have a mdintlist as multidimensional dynamically allocated arrays. the type definition should be something like this:

typedef struct Mdintlist{
    intlist d // dimension of the array
    /* second part */
}mdintlist;

there are several options for the second part. on option is that to have a pointer towards a mdintlist of lower dimension like

struct Mdintlist * c;

the other options is to use void pointers:

void * c;

I don't know how to continue it from here.

P.S. one solution could be to allocate just one block of memory and then call the elements using a function. However I would like to call the elements in array form. something like tmpmdintlist.c[1][2][3]...

Hope I have explained clearly what I want.

P.S. This is an ancient post, but for those who may end up here some of my efforts can be seen in the Cplus repo.

Upvotes: 2

Views: 123

Answers (2)

Dellowar
Dellowar

Reputation: 3352

Well, if you separate the pointers and the array lengths, you end up with much less code.

int *one_dem_array;
size_t one_dem_count[1];

int **two_dem_array;
size_t two_dem_count[2];

int ***three_dem_array;
size_t three_dem_count[3];

This way you can still use your preferred notation.

int num_at_pos = three_dem_array[4][2][3];

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You can't! you can only use the function option in c, because there is no way to alter the language semantics. In c++ however you can overload the [] operator, and even though I would never do such an ugly thing (x[1][2][3] is alread y ugly, if you continue adding "dimensions" it gets really ugly), I think it would be possible.

Upvotes: 2

Related Questions