Values changed in previous arrays without intention

Dear
My code is quite complex so it is not possible to put it here and explain every thing.
Why generally the values in the some arrays get changed through coding while I have not did that manually?
Any possible reasons?
Regards


Most likely you're accidentally accessing your arrays incorrectly. For example,
1
2
int array[10];
array[10] = 5;
These kinds of bugs are generally the hardest to locate.
computers are stupid, they do what you tell them to do.


watch your array to see where it changes
https://stackoverflow.com/questions/11004374/watch-a-memory-range-in-gdb
Try to utilize the const keyword whenever possible.

For example, when you pass an array to a function that should not modify the array, use const like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void doNotChangeArray(const int array[], int size) {
    array[0] = 4;   // Error - attempting to modify const parameter

    int localVar = array[0];    // Acceptable - this is read-only
}

int main()
{
    int array[3] = {1, 2, 3};

    doNotChangeArray(array, 3);

    std::cout << array[0];
    return 0;
}



When you have an array as a member variable of a class, you can again use the const keyword to mark a member function as non-mutator, so that function cannot modify the array.
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
class Foo {
    int array[3];

public:
    void doNotChangeArray() const {
        array[0] = 6;   // Error - attempting to modify member variable in const function
    }

    int & getElementAt(int index) const {
        if(index < 3 && index >= 0) {
            return array[index];
        }
    }
};

int main()
{
    Foo foo;

    foo.doNotChangeArray();

    foo.getElementAt(0) = 7;    // Error - discards qualifiers

    std::cout << foo.getElementAt(0);
    return 0;
}


I think that should minimize accidental changes to arrays.
@mpark4656 that's a good advise. It's sometimes tiresome so add extra code to your build, it pays out on time saved on the long run.
closed account (E0p9LyTq)
My code is quite complex so it is not possible to put it here and explain every thing.

Well, since we have no idea of what your code is doing (or not doing), let's blame the problems on gremlins.
Topic archived. No new replies allowed.