# Arbitrary length multi-dimensional arrays

• 06-26-2006
thw
Arbitrary length multi-dimensional arrays
Newbie question here. It's been a while since I've done C programming,
and I hit a wall last night.

Let's say I have a three dimensional array, like so:
Code:

```int p[2][3][3] = {{{0,0,0}, {1,1,1}, {0,1,0}}, {{0,1,0}, {1,1,0}, {0,1,0}}};```
I also have a number of other three dimensional arrays, generated with
a code generating script. The size of each dimension varies with each
one. Some are [5][3][3], some are [2][5][5], etc...

How would I declare a variable that could hold any of these
3-dimensional arrays? I'm tripping over the pointer syntax.

I'd like to be able to do something like:
int ***val = p; //The variable p from the last example.

I'm pretty sure that ***val is the wrong way to go about it.

• 06-26-2006
Dave_Sinkula
• 06-26-2006
itsme86
One way would be dynamic memory allocation. Let's say your program knows how big each dimension is and they're stored in the variables s_dim1, s_dim2, s_dim3. You could do something like this:
Code:

```{   int ***p;   int s_dim1 = 4, s_dim2 = 5, s_dim3 = 2;   int i, j;   p = malloc(sizeof(*p) * s_dim1);   for(i = 0;i < s_dim1;++i)   {     p[i] = malloc(sizeof(**p) * s_dim2);     for(j = 0;j < s_dim2;++j)       p[i][j] = malloc(sizeof(***p) * s_dim3);   } }```
There isn't any way to just make an array in C without giving it a size, so the dynamic memory allocation is probably the best way to go.

Disclaimer: I didn't test the above code, but it should work.
• 11-22-2006
darsunt
Here is code that's tested for two dimensional array

int **array1 = (int **)malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = (int *)malloc(ncolumns * sizeof(int));

access allocated 2D array like: array1[1][2] = 5;
• 11-22-2006
Salem