Problem with dynamic array class

Jan 18, 2016 at 7:24pm
I don't know what the problem is, but my code is not working for some reason.
Anybody sees where the problem is?

I just want to make an dynamic array and then make it longer and then add numbers in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>

using namespace std;

class A
{
    int length;
    int maxlength = 10;
    double *a;

public:

    A(int length = 5)
    {
        if(length < 1 || length > maxlength)
            cout << "Invalid input." << endl;
        else
            this-> length = length;

        this-> a = new double[this-> length];
    }

    void put(int pos, double num)
    {
        if(pos < 0 || pos > this-> length)
            cout << "Invalid input." << endl;
        else
            a[pos] = num;
    }

    void longer(int length)
    {
        if(this-> length + length > maxlength)
            cout << "Array can't be longer than 10." << endl;
        else
            this-> length += length;
    }

    void print()
    {
        for(int c = 0; c < this->length; c++)
        {
            cout << a[c] << " ";
        }
        cout << endl;
        cout << length;
    }

    ~A()
    {
        delete [] a;
    }
};

int main()
{
    A x(5);
    x.longer(5);
    x.put(0,1);
    x.put(1,2);
    x.put(2,3);
    x.put(3,4);
    x.put(4,5);
    x.put(5,6);
    x.put(6,7);
    x.print();
}
Jan 18, 2016 at 7:29pm
In the longer function you need to allocate a new bigger array if you want to be able to store more elements.
Jan 18, 2016 at 7:42pm
Oh so i need to delete array a and make it again with new length ?

I fixed it like this:

1
2
3
4
5
6
7
8
9
10
void longer(int length)
    {
        if(this-> length + length > maxlength)
            cout << "Array can't be longer than 10." << endl;
        else
            this-> length += length;

            delete [] a;
            a = new double[this->length];
    }


Do i need to delete it or i can just say :
 
a = new double[this->length];
Last edited on Jan 18, 2016 at 7:44pm
Jan 18, 2016 at 9:14pm
Yes, you need to delete it, otherwise you'll have a memory leak.

Note that if you don't want to lose the values that was stored in the old array you need to copy them to the new array before deleting the old array.
Topic archived. No new replies allowed.