Hello,

Please help me to overcome the following confussion.
Suppose I have created an array of pointers like,

A** l_aAPtr = new A*[l_iTotal];
for(int i = 0; i<l_iTotal;i++)
{
    l_aAPtr[i] = new A();
}

Now I want to delete this array. Please advise which of the following way is correct

1.

for(int k = 0; k<l_iTotal;k++)
{
    if(l_aAPtr[k])
    {
            delete l_aAPtr[k];                
            l_aAPtr[k] = 0;
    }
}
if(l_aAPtr)
{
    delete l_aAPtr;           
    l_aAPtr = 0;
}

2.

for(int k = 0; k<l_iTotal;k++)
{
    if(l_aAPtr[k])
    {
            delete l_aAPtr[k];                
            l_aAPtr[k] = 0;
    }
}
if(l_aAPtr)
{
    delete [] l_aAPtr;           
    l_aAPtr = 0;
}

Thanks in advance,

Amit M.

Recommended Answers

All 3 Replies

The second is more correct. When you say new[], you should use delete[], when you say new, you should use delete. They can't be mixed and matched.

The second one is because l_aAPtr is an array.

Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.