Thread: Array of Pointers + Deleting An Object = Problems

  1. #1
    Registered User
    Join Date
    Feb 2004
    Posts
    15

    Array of Pointers + Deleting An Object = Problems

    Hi there,

    I have an array of pointers to objects, and I wish to delete an object pointed to by one of the elements. However, when I try to do this using delete MyPtrArray[2]; my program crashes at runtime. The object pointed to by MyPtrArray[2] definitely exists, as I can access the object's data via the pointer. Am I using delete incorrectly here?

    Thanks!

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    The code below works fine, so you'll have to show more of your code to see what you are doing wrong.
    Code:
    int main()
    {
        const int arraySize = 5;
    
        int* MyPtrArray[arraySize];
        for (int i=0; i < arraySize; i++)
            MyPtrArray[i] = new int(i);
    
        delete MyPtrArray[2];
    
        MyPtrArray[2] = 0; // Set to null after delete.
        for (int j=0; j < arraySize; j++)
            delete MyPtrArray[j];
    }
    By the way, do you know when your program crashes at run time? Is it after or during the delete. If it is after, it is quite possible that you are trying to use the pointer that you deleted after you delete it.
    Last edited by jlou; 03-04-2004 at 10:48 AM.

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Or perhaps the object's desctructor is causing the problem......
    Use your debugger to pinpoint where the crash is occuring for more clues.

    gg

  4. #4
    Registered User
    Join Date
    Feb 2004
    Posts
    15
    Thanks CodePlug, you were exactly right, it was a problem in the destructor. I guess I should've checked there first...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Syntax for constant array of array pointers
    By BMintern in forum C Programming
    Replies: 4
    Last Post: 05-14-2008, 08:21 AM
  2. C Pointers Problems
    By mhelal in forum C Programming
    Replies: 8
    Last Post: 01-10-2007, 06:35 AM
  3. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  4. Array of pointers help
    By Unregistered in forum C Programming
    Replies: 10
    Last Post: 02-14-2002, 12:37 PM
  5. Array of pointers
    By falconetti in forum C Programming
    Replies: 5
    Last Post: 01-11-2002, 07:26 PM