Arrays of Pointers

This is a discussion on Arrays of Pointers within the C++ Programming forums, part of the General Programming Boards category; Will this produce a memory leak? Code: #include <iostream.h> 4: 5: class CAT 6: { 7: public: 8: CAT() { ...

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

    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,764
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 03: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, 04: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21