Is it "ok" to store elements in an array this way?

The reason why i want to do this instead of a vector or any other easier solutions isn't important. Someone told me that it's not ideal, because if a variable reallocates it's memory address, it's going to cause errors. He also told me it may reallocate when you do this:

a=func(a);

How does it work? Can this happen during run-time with dynamically allocated values?




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
#include <iostream>

using namespace std;

int main()
{
    int const ** arr = new const int*[4](); /* I need the const to be able to store const and non-const variables */

    int a = 10;
    const int b = 20;
    int* c = new int(30);
    int const* d = new  int(40);

    arr[0] = &a;
    arr[1] = &b;
    arr[2] = c;
    arr[3] = d;

    cout << &a << endl;
    cout << &b << endl;
    cout << c << endl;
    cout << d << endl;

    for (int i = 0; i<4; i++)
        cout << "Memory address: " << arr[i] << "\tValue: " << *arr[i] << endl;

    *(const_cast<int*>(arr[0])) = 100; /* I'll use the originally non-const variables with this later, but never on originally const values. */

    return 0;
}
If you don't believe this someone, why don't you test it ?

I mean really, if your not going to believe someone, are you going to believe someone else ?
Last edited on
> Is it "ok" to store elements in an array this way?

No, it is not "ok".
In the sense that code of this kind will never see the light of day (other than on github) because it would never pass a code review.
This kind of using array will work but it can lead into a lot of errors in the future, and then it is going to be a bit late and very troubling. Try to avoid from those kind of assigning. I think it is important to code knowing how to avoid errors and make your code as simple as you can. That way you can avoid those errors. If you think it's too hard there are programs who help detecting errors for you. I used to work with checkmarx but not sure about their cost today.
Anyway, wish you luck!
Ben.
if a variable reallocates it's memory address,

what is this supposed to mean?
Topic archived. No new replies allowed.