c++ class member variable changing without explicitly being modified

I am trying to implement a heap. I have built a class to store an array of integers, the number of ints currently in the array and the total size of the array. When I invoke the insert method, the total size variable gets changed but the code does not explicitly do it. The code is as follows:

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
class Heap
{
    public:
        Heap(int);
        void insert(int);

    private:
        int int_array[];
        int max_length;
        int length;
};
void Heap::insert(int key)
{
    //max length before the insertion
    cout << "max length " << max_length << endl;
    if (length <= max_length) {
        int_array[length] = key;
        //max length after insertion
        cout << "max length " << max_length << endl;
        length++;
    }
}

Heap::Heap(int N)
{
    int_array[N];
    max_length = N-1;
    length = 0;
}

int main()
{
    Heap h(100);
    h.insert(10);
    return 0;
}


The code prints the following when executed:
max length 99
max length 10

Max length should still be 99 on the second line. What am I doing wrong?
You're overwriting memory, that's why. Arrays can't be made dynamically like that, you have to use new and delete. For proof of the memory overwriting, try changing line 34 to insert 42 instead of 10.
Last edited on
That program can't even be compiled with a standards-conforming C++ compiler (line 8 is a syntax error).

Based on what it appears to be trying to do, you need to use vectors:

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
#include <iostream>
#include <vector>
#include <algorithm>
class Heap
{
 public:
    Heap(int);
    void insert(int);
 private:
    std::vector<int> int_array;
};

void Heap::insert(int key)
{
    int_array.push_back(key);
    std::push_heap(int_array.begin(), int_array.end());
}

Heap::Heap(int N) : int_array(N) {}

int main()
{
    Heap h(100);
    h.insert(10);
}
Topic archived. No new replies allowed.