If
my_array
must be of type
int
then that is going to be difficult to achieve. If, however, you can let
my_array
be of type
int*
then it can be done like this;
#include<iostream>
struct fresh
{
int value;
};
int main()
{
fresh foo[4];
int* my_array[4] = {
&foo[0].value,
&foo[1].value,
&foo[2].value,
&foo[3].value,
};
foo[2].value = 32;
std::cout << "foo[2].value==" << foo[2].value << "==" << *my_array[2] << std::endl;
return 0;
}
Also, remember
arrays are evil[
^] so if you want this to work with variable number of elements you're better off using a
std::vector
:
#include<iostream>
#include<vector>
using namespace std;
struct fresh
{
int value;
fresh(const int& value) {
this->value;
}
};
int main()
{
vector<fresh> foo;
vector<int*> my_array;
foo.push_back(fresh(1));
foo.push_back(fresh(2));
foo.push_back(fresh(3));
foo.push_back(fresh(4));
foo.push_back(fresh(5));
foo.push_back(fresh(6));
for(int i = 0; i < foo.size(); ++i) {
my_array.push_back(&foo[i].value);
}
foo[2].value = 32;
std::cout << "foo[2].value==" << foo[2].value << "==" << *my_array[2] << std::endl;
return 0;
}
Hope this helps,
Fredrik