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?

7
  • @BlackBear that is an answer, not a comment. Commented Feb 5, 2011 at 23:20
  • IMO, this is poor idea. See the code in: stackoverflow.com/questions/2216017/… for an alternative. Commented Feb 5, 2011 at 23:22
  • @Radek: lol if I knew before I wouldn't post my answer. xD Commented Feb 5, 2011 at 23:24
  • 2
    In C++, you should almost always prefer the safety of std::vector<T> to manually managing memory. Commented Feb 5, 2011 at 23:24
  • @SethJohnson I agree wholeheartedly, but I'm modifying old code and rewriting everything is not an option. Commented Feb 6, 2011 at 14:31

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@sdfqwerqaz: pointers are a mess. Me neither was sure it would work.. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.