Thread: Correctly initialize 2-d array

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    186

    Correctly initialize 2-d array

    I'm trying to set up a 2-d array of objects. I want the array to be accessible to the whole class that it is defined in but I don't know how big the array is right away. What is the correct way to do this? I don't think the way I have it now is correct:

    Code:
    class Game
    {
         private:
              MyObject* myArray;
    
         public:
              Game(int rows,int cols)
              {
                   myArray[rows][cols];
              }
    }
    Is this right?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    There is more than one "correct" way. Since the size is not known at compile time, you need a dynamic array.

    I'd always recommend a vector instead of a dynamic array allocated with new[] because the vector initializes, destroys and copies itself properly and a dynamic array with new[] does none of that.

    A 2-d array can be implemented with a vector of vectors. (You can also use a single vector or a single dynamic array, but there's probably little reason to add that complexity into your program right now.)

    So I'd look up the syntax for vector and see if you can figure out how to create one normally. Then try to make it a member variable initialized in the constructor.

    If you can't use vector, then you need to make myArray a double pointer. (Again, you can use a single pointer but there's no need to add that complexity.) Next you'd need to add code inside the constructor to call new on the first array, then a loop to call new for all the inside arrays. You'd then want to make sure to add similar code in the destructor to delete the arrays and you'd want to disable the copy constructor and copy assignment operator. Those things are all handled automatically with vector, which is why you should use that if you can.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Location
    While(1)
    Posts
    377
    As Daved is right vector will be good option in ur case....


    But if u want to use myArray the size depends on your requirement and about using

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. cannot print out my 2d array correctly! please help
    By dalearyous in forum C++ Programming
    Replies: 5
    Last Post: 04-10-2006, 02:07 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM