dynamic allocating array

I am dynamically allocating a 3D array like so

float* Array = new float[height*width*depth];

I need to dynamically the 3D array because it is very big (about 500x500x500).

I would like to write the array as something like

float* Array = new float[height][width][depth];

to make indexing easier. Why does this not work? How can I dynamically allocate an array like this so I can index easier?
For 3 D array, you need to take triple pointer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int ***array 3D;
int i, j, k;
i = height;
j = width;
k = depth;
//  Allocate 3D Array
array3D = new int**[x];
for(i = 0; i < x; i++)
{
array3D[i] = new int*[y];
for(j = 0; j < y; j++)
{
      array3D[i][j] = new int[z];
      }}
      // [i][j][k] means kth element of ith row and jth clumn, which itself is an array now
// You can fill array by using same loop and giving values
array3D[i][j][k] = value;
//In the same way deallocate the memory 


I hope it helps
Good Luck!!!
Last edited on
if you want 3D array where all dimensions will be of a different size then have a look at this example:
http://www.cplusplus.com/forum/general/53785/
This is begging to be done with proper C++ containers. It removes all that messing around manually with memory, and gives the standard library container functions to play with. Here's an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <vector>
#include <iostream>
using std::vector;

int main() {
  vector<vector<vector<double> > > array3D;

  int height, width, depth;

  std::cin >> height;
  std::cin >> width;
  std::cin >> depth;

  // Set up sizes
  array3D.resize(height);
  for (int i = 0; i < height; ++i) {
    array3D[i].resize(width);

    for (int j = 0; j < width; ++j)
      array3D[i][j].resize(depth);
  }

  // Put some values in
  array3D[1][2][5] = 6.0;
  array3D[3][1][4] = 5.5;

  return 0;
}


Last edited on
You could make a wrapper for the 1D array
1
2
3
4
5
6
value_type& matrix3d::operator()(int K, int L, int M){
  return array[ (K*colum+L)*depth + M];
}

//using
m(K,L,M);
Topic archived. No new replies allowed.