0

I have a pointer to a 2d array of Robot class

Robot ***rob; 

And below is my code for the constructor. The constructor works fine, but now I am trying to build a destructor to delete this pointer and it keeps on crashing the program!

My question is, how can I delete the pointer to the 2d array of robots?

RobotsWorld::RobotsWorld(int x , int y)
{
    X=x;Y=y; // returns the limitation of the matrix 
    rob = new Robot**[x];
    for(int i = 0; i < x; i++)
    {
        rob[i] = new Robot*[y];

        for(int j = 0; j < y; j++)
        {
            rob[i][j] = NULL;
        }
    }
}
2
  • you're settings the pointer to null, not deleting it. Commented Nov 23, 2012 at 16:44
  • 2
    you are doing one of the most dangerous things that you can do with a pointer, setting it to NULL when you are thinking about deleting it; you probably want to adopt the smart pointers and save yourself a lot of troubles. Commented Nov 23, 2012 at 16:58

1 Answer 1

1
// Code is not tested
for(int i = 0 ; i < x ; ++i)
{
    for(int j = 0 ; j < y ; ++j)
    {
        delete rob[i][j];
    }
    delete[] rob[i];
}
delete[] rob;

By the way, why do you set rob[i][j] = NULL; ?

I think it should be : rob[i][j] = new double;

Sign up to request clarification or add additional context in comments.

1 Comment

i tried doing that , but the program still crashes , when it enters the delete[] rob[i][j]; while the value is null it is cool , otherwise it crash :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.