Reputation: 23
I realize this code is silly, but it is a simplified version of my problem. The code below prints out 10 10's, what I would like it to do is print out the numbers 0 through 9, which were the values j was pointing at when j was added to the vector. How can I keep the pointer stored in the vector pointing to the original integer value it was pointing to when it was stored?
int main()
{
std::vector<int*> test;
int *j;
for (int i = 0; i < 10; i++)
{
j = &i;
test.push_back(j);
}
for (int i = 0; i < 10; i++)
{
std::cout << *test[i] << std::endl;
}
return 0;
}
Upvotes: 0
Views: 203
Reputation: 41
You can point to elements of another container:
std::vector<int*> test; // holding pointers
std::array<int, 10> ray; // holding values
std::iota(ray.begin(), ray.end(), 0) // 0, 1, 2, 3..
for (int i = 0; i < 10; i++)
{
int *j = &ray[i];
test.push_back(j);
}
Upvotes: 1
Reputation: 4145
I'm pretty sure you're looking for this
int main()
{
std::vector<int> test;
int *j;
for (int i = 0; i < 10; i++)
{
j = &i;
test.push_back(*j);
}
for (int i = 0; i < 10; i++)
{
std::cout << test[i] << std::endl;
}
return 0;
}
So.... I've changed 'test' to be a vector of integer values, not pointers, and I've dereferenced the pointer 'j' before storing it in the vector. And I've adjusted the print routine to print the value
Upvotes: 1
Reputation: 15446
For this simple example pointers aren't even necessary! We can simply do
std::vector<int> test;
for (int i = 0; i < 10; i++)
{
test.push_back(i);
}
However, if you insist on using pointers like you are...you currently have Undefined Behavior.
After the loop ends, i
goes out of scope and your pointers are pointing to memory you no longer own. What you want can be accomplished by using dynamically allocated memory. We can allocate a new integer for each value of the vector:
std::vector<int*> test;
int *j;
for (int i = 0; i < 10; i++)
{
j = new int(i);
test.push_back(j);
}
Just remember that you'll have to deallocate the memory yourself after you're done!
for (int i = 0; i < 10; i++)
{
delete test.at(i);
}
Upvotes: 1