0

I am trying to create a dynamic 3D array using C. the idea is to create a 3D array which looks like something like this

A[0][128][128]
A[1][64][64]
A[2][32][32]
A[3][16][16]
A[4][8][8]
.....
A[n][1][1]

n,128,128 are the inputs.

can anyone suggest how to do this?

jonayat
  • 21
  • 3
  • That's not a jagged array, if the sub-dimensions are all constant size. Just say `new AType[n][128][128]`, surely? See also this question: http://stackoverflow.com/questions/62512 and http://stackoverflow.com/questions/8902055 – Ben Feb 09 '12 at 13:38
  • I just used sub-dimensions same as an example, they can be different in the actual program. sorry for not making that clear. Anyways, got it working now.. @unwind: yeah, its kind of mip-map i guess..Actually I was writing a code for multi grid method. A was the matrix that stores all the values for different grids – jonayat Feb 10 '12 at 10:30

1 Answers1

0

The following function allocates the memory for your dynamic array. elem_size is the size for each element, n refers to the size of the first dimension, the other two dimensions are sized 128.

void* create_3Darray(size_t elem_size, size_t n) {
    return malloc(elem_size * n * 128 * 128);
}

Usage:

int ***arr = create_3Darray(sizeof(int), 256);
arr[2][5][12] = 12;

You can substitute malloc with calloc to initialize the elements to 0, otherwise the array might be filled with random values.

Also you should be careful not to read/write over the arrays/dimensions bounds.

Constantinius
  • 34,183
  • 8
  • 77
  • 85
  • If I am understanding right, I will still have a 3D array like arr[0][5][12] ; arr[1][5][12] ; arr[2][5][12] ..so in this case I still have a 5X12 2D array for each arr[n] What I am trying to do is probably a jagged 3D array – jonayat Feb 09 '12 at 21:34
  • Yes, you are right, it is a simple 3D array, and not jagged. For a jagged array you'd need size information for each sub-array which has to be passed to the allocation function. – Constantinius Feb 10 '12 at 09:17
  • Got it working, had to change the dims inside the for loops. Thanks – jonayat Feb 10 '12 at 10:26