0

I need to store an array on heap since I got a seg fault when running the program, due to it being too large. Normally this would be easy, but in this case it is a multidimensional array (3D specifically) and it's a variable length array too.

I tried to fit this answer for a 2D array (which I'm pretty sure works because I found it on another answer on SO) into one for a 3D array

int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
    ary[i] = new int[sizeX];
}

by doing this:

  double **isoarray = new double*[nBinsX];
  for(int xi = 0; xi < nBinsX; ++xi){
    isoarray[xi] = new double[nBinsY];
    for(int yi = 0; yi < nBinsY; ++yi){
      isoarray[xi][yi] = new double[nShuffles];
    }
  }

Where I should mention that the array is meant to have dimensions nBinsX x nBinsY x nShuffles, but it isn't working, nor did I really think it would to be honest. Can anyone offer a suggestion on how I would do this? Thanks in advance!

  • 1
    Don't you need a triple-pointer? One level of pointer for a 1D array; two levels of pointer for a 2D array; and … let's think … oh, maybe three levels for a 3D array? – Jonathan Leffler Sep 24 '15 at 04:58

1 Answers1

0

Rather than heap-allocating arrays of pointers to more heap-allocated arrays and so on, you should make a single giant allocation and do appropriate indexing. This is a common technique:

double *isoarray = new double[nBinsX * nBinsY * nShuffles];

If you want to make a nice C++ solution out of it, store that pointer in a class which has an indexing method something like this:

double& at(x, y, shuffle) {
  return isoarray[x * nBinsY * nShuffles + y * nShuffles + shuffle];
}

This way you have a single contiguous allocation which is better for performance when allocating, when using, and when deallocating. You can play with the indexing in terms of which dimension comes "first" to achieve even better performance depending on which way you usually traverse the data.

AlfaVector
  • 73
  • 4
John Zwinck
  • 239,568
  • 38
  • 324
  • 436