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?
#include <iostream>
usingnamespace std;
int main()
{
intconst ** arr = newconstint*[4](); /* I need the const to be able to store const and non-const variables */
int a = 10;
constint b = 20;
int* c = newint(30);
intconst* d = newint(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;
}
> 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.