the memory allocated depends on what the user enters

closed account (jvqpDjzh)
how to delete the memory pointed by a pointer if the memory allocated depends on what the user inputs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Array::Array (int _length)//the length could be 1!
{
    if (_length > 0) {
        length = _length;
        ptr = new int[length];
        for (int i = 0; i < length; i++)
            ptr[i] = 0;
    }
}

Array::~Array()
{
    if(ptr != NULL){//I am not sure if this control has sense
       if(length == 1) delete ptr;
//Is this correct? 
//Or we dont't have to control if length == 1 and just delete[] ptr?
       
      else delete [] ptr;
    }
}


Last edited on
You don't have to control if length = 1.

In your constructor, why are you checking the value of length? The constructor is called when you're instantiating an object, and so you haven't done anything to it before. It could contain garbage or some negative number that will cause your code to not execute at all.

EDIT: Maybe you meant to check _length instead.
Last edited on
closed account (jvqpDjzh)
If you create an array with just 1 element, we have to use delete[] ptr or delete ptr?

EDIT: I have changed it, I just made a mistake typing
Last edited on
You would use delete[] ptr.
Topic archived. No new replies allowed.