0

My intention is to create a dynamic 3D array in C++ using pointers.

MyType*** myArray;
myArray = new MyType**[GRID_SIZE];
for (int i = 0; i < GRID_SIZE; ++i) {
  myArray[i] = new MyType*[GRID_SIZE];
  for (int j = 0; j < GRID_SIZE; ++j) {
    myArray[i][j] = new MyType[GRID_SIZE];
  }
}

Now this 3D array is ready to store MyType instances. What is the correct syntax needed when declaring this array if I want to store pointers to MyType instead of just MyType objects in this array?

sdfqwerqaz1
  • 1,447
  • 2
  • 10
  • 8
  • @BlackBear that is an answer, not a comment. –  Feb 05 '11 at 23:20
  • IMO, this is poor idea. See the code in: http://stackoverflow.com/questions/2216017/dynamical-two-dimension-array-according-to-input/2216055#2216055 for an alternative. – Jerry Coffin Feb 05 '11 at 23:22
  • @Radek: lol if I knew before I wouldn't post my answer. xD – BlackBear Feb 05 '11 at 23:24
  • 2
    In C++, you should almost always prefer the safety of `std::vector` to manually managing memory. – Seth Johnson Feb 05 '11 at 23:24
  • @SethJohnson I agree wholeheartedly, but I'm modifying old code and rewriting everything is not an option. – sdfqwerqaz1 Feb 06 '11 at 14:31
  • @sdfq: You're clearly trying to write your "dynamic 3D array" from scratch, for which you should use `std::vector`. If something else in your program absolutely needs a pointer to an array of floats, then you could perhaps pass it `&(innervec.front())` while making sure that your `vector > > >` isn't destroyed. – Seth Johnson Feb 06 '11 at 16:51
  • @SethJohnson I am replacing an existing array allocated on the stack with this version allocated on the heap. I will try using std::vector instead. – sdfqwerqaz1 Feb 06 '11 at 18:59

1 Answers1

3

Simply add another * to your declaration, but don't call new on it.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • I was of course absolutely sure that I had done that and that it didn't work. Well, I tried again and now it worked so I was obviously doing something crazy the first time. This is my dumbest question to date. I'll go and stand in the corner now. – sdfqwerqaz1 Feb 06 '11 at 12:01
  • @sdfqwerqaz: pointers are a mess. Me neither was sure it would work.. ;) – BlackBear Feb 06 '11 at 12:29