Thread: Arrays of Pointers

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    Arrays of Pointers

    Will this produce a memory leak?
    Code:
    #include <iostream.h>
    4:
    5:     class CAT
    6:     {
    7:        public:
    8:           CAT() { itsAge = 1; itsWeight=5; }   
    9:           ~CAT() {}                                 // destructor
    10:          int GetAge() const { return itsAge; }
    11:          int GetWeight() const { return itsWeight; }
    12:          void SetAge(int age) { itsAge = age; }
    13:
    14:       private:
    15:          int itsAge;
    16:          int itsWeight;
    17:    };
    18:
    19:    int main()
    20:    {
    21:       CAT * Family[500];
    22:       int i;
    23:       CAT * pCat;
    24:       for (i = 0; i < 500; i++)
    25:       {
    26:          pCat = new CAT;
    27:          pCat->SetAge(2*i +1);
    28:          Family[i] = pCat;
    29:       }
    30:
    31:       for (i = 0; i < 500; i++)
    32:       {
    33:          cout << "Cat #" << i+1 << ": ";
    34:          cout << Family[i]->GetAge() << endl;
    35:       }
    36:     return 0;
    37: }
    and mybe I should add folowing lines:
    Code:
    for (i = 0; i < 500; i++)
           {
    CAT *p;
    p=Family[i];
    delete p;
             }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    What's with all the temp variables?

    Family[i] = new Cat;
    Family[i]->SetAge(2*i +1);

    Then, as you surmised a loop doing
    delete Family[i];
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with returning arrays using pointers
    By cuba06 in forum C Programming
    Replies: 9
    Last Post: 11-23-2007, 10:40 AM
  2. Array of Pointers to Arrays
    By Biozero in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 02:31 PM
  3. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 04:49 PM
  4. pointers and arrays..
    By ahming in forum C Programming
    Replies: 1
    Last Post: 04-24-2004, 03:12 AM
  5. Stack functions as arrays instead of node pointers
    By sballew in forum C Programming
    Replies: 8
    Last Post: 12-04-2001, 11:13 AM