Thread: A pointer to an array of object pointers, which point to objects

  1. #1
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    367

    A pointer to an array of object pointers, which point to objects

    Hi, say i have got the following class called X. I want to be able to create a pointer to an array of type X pointers, which then be instantiated into objects. I have tried the follwing, but with no success. Any help would be greatly appreciated.

    Code:
    int NumObjs = 2;
    
    X **Test;
    
    *Test = new X[NumObjs];
    
    for(int ObjNum; ObjNum < NumObjs; ObjNum++)
      Test[ObjNum] = new X(/*Whatever*/);
    I need to be able to access the objects using the following notation: Test[0]->Member; Thanks.
    Be a leader and not a follower.

  2. #2
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    First you allocate NumObj X *'s, then loop through those pointers and allocate real X's :-)
    Code:
    #include <iostream>
    
    using namespace std;
    
    class X {
    public:
      int stuff;
    };
    
    namespace {
      const int NumObj = 2;
    }
    
    int main()
    {
      X **test;
    
      test = new X *[NumObj];
    
      for (int i = 0; i < NumObj; i++)
      {
        test[i] = new X;
      }
    
      // Use and delete
    }
    /*
    test->[0]->X Obj
          [1]->X Obj
    */
    *Cela*

  3. #3
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    367
    Cela, you are fantastic, wonderful, amazing, and everything else. You don't know what a headache i've had with that. Again, thank you so much yet again! YES!!!!!!!!!!!!!!!! IT WORKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Be a leader and not a follower.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. sorting with pointer of pointers to array
    By dunpealslyr in forum C++ Programming
    Replies: 6
    Last Post: 10-01-2007, 11:26 PM
  3. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  4. Replies: 41
    Last Post: 07-04-2004, 03:23 PM
  5. Creating an array of object pointers
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2001, 10:01 PM