3d dynamic array in continuous memory

Hi. I am trying to create a 3d array in one block of memory. The following code compiles ok but gives a segmentation fault at runtime. Any ideas appreciated!

const int LAYER1 = 5;
const int LAYER2 = 4;
const int ELEMENTS_PER_ARRAY = 3;
int i, j, k;

int *mem_alloc = new int[LAYER1 * LAYER2 * ELEMENTS_PER_ARRAY];
int ***three_d = new int**[LAYER2 * ELEMENTS_PER_ARRAY];

for ( i = 0; i < LAYER1; i++ ) {
for ( j = 0; j < LAYER2; j++ ) {
three_d[i][j] = &mem_alloc[(i+1) * j * ELEMENTS_PER_ARRAY];
}
three_d[i] = &three_d[i][0];
}

/* to test funcionality give each element of mem_alloc a value */
for ( i = 0; i < LAYER1 * LAYER2 * ELEMENTS_PER_ARRAY; i++ ) {
mem_alloc[i] = i;
}

/* Then access the values as per a multidimensional array */
for ( i = 0; i < LAYER1; i++ ) {
for ( j = 0; j < LAYER2; j++ ) {
for ( k = 0; k < ELEMENTS_PER_ARRAY; k++ ) {
cout << "test: " << three_d[i][j][k] << endl;
}
}
}
You are allocating your main array properly (1st layer).
You are also allocating the int** array (3rd layer) - although you are allocating too much.
However you are not allocating the int* arrays at all (2nd layer).

If you really want to do this, you could do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int* mem_alloc = new int[LAYER1 * LAYER2 * ELEMENTS_PER_ARRAY];
int** three_d = new int*[LAYER1];

for(int i = 0; i < LAYER1; ++i)
{
  three_d[i] = new int*[LAYER2];
  for(int j = 0; j < LAYER2; ++j)
    three_d[i][j] = &mem_alloc[((i * LAYER2) + j) * ELEMENTS_PER_ARRAY];
}

// OK to use 'three_d[z][y][x]' now


// cleanup:
for(int i = 0; i < LAYER1; ++i)
  delete[] three_d[i];
delete[] three_d;
delete[] mem_alloc;




But for the love of God, if you are using a 1D array anyway, there is no point to having the int** and int* arrays. Just wrap access behind a class interface so you can have simpler syntax.

See the end of this post for an example class:

http://cplusplus.com/forum/articles/17108/#msg85595
Last edited on
Thanks for the help. I know its a bit awkward but its a problem for college that i have to solve in this fashion
Topic archived. No new replies allowed.