Allocate 6xNxN array

Viewed 472

I have a variable N. I need a 6xNxN array.

Something like this:

int arr[6][N][N];

But, obviously, that doesn't work.

I'm not sure how I'd go about allocating this so that I can access, e.g. arr[5][4][4] if N is 5, and arr[5][23][23] if N is 24.

Note that N will never change, so I'll never have to reallocate arr.

What should I do? Will int ***arr = malloc(6 * N * N * sizeof(int)); work?

4 Answers

Making a simple change to the declaration on this line and keeping the malloc can easily solve your problem.

int ***arr = malloc(6 * N * N * sizeof(int));

However, int *** is unnecessary (and wrong). Use a flat array, which is easy to allocate:

int *flatarr = malloc(6 * N * N * sizeof(int));

This works for three dimensions, and instead of accessing arr[X][Y][Z] as in the question, you access flatarr[(X*N*N) + (Y*N) + Z]. In fact, you could even write a handy macro:

#define arr(X,Y,Z) flatarr[((X)*N*N) + ((Y)*N) + (Z)]

This is basically what I've done in my language Cubically to allow for multiple-size cubes. Thanks to Programming Puzzles & Code Golf user Dennis for giving me this idea.

Related