#include <iostream>
#include <vector>
using namespace std;
class CNum {
public:
CNum(int _value) : Value(_value) {}
int Value;
};
vector<CNum*> Nums;
void find_num(int _n, CNum* _pointer) {
vector<CNum*>::iterator i;
for(i = Nums.begin(); i != Nums.end(); ++i) {
if((*i)->Value == _n) _pointer = *i;
}
cout << "original address: " << _pointer << endl;
cout << _pointer->Value << endl;
}
int main() {
Nums.push_back(new CNum(1));
Nums.push_back(new CNum(2));
Nums.push_back(new CNum(3));
CNum* target;
find_num(2, target);
cout << "new address(?): " << target << endl;
cout << target->Value << endl;
return 0;
}
[SOLVED]A problem related to vectorpointer
The output is something like below:
original address: 0x3d3770
2
new address(?): 0x289d720
Plus an error message from the system.
And the source:
How come the address changes after the return of the function find_num?
In your code, the value of target never changes.
In particular, the value of target is not changed by the find_num(2, target); code. This is because a copy of target is passed to find_num (which takes its second argument by value), and the passed copy is modified without altering the original.
In particular, the value of target is not changed by the find_num(2, target); code. This is because a copy of target is passed to find_num (which takes its second argument by value), and the passed copy is modified without altering the original.
Thank you.
The problem is solved by simply change "find_num(int _n, CNum* _pointer)" to "find_num(int _n, CNum*& _pointer)".
The problem is solved by simply change "find_num(int _n, CNum* _pointer)" to "find_num(int _n, CNum*& _pointer)".
Your program has memory leaks. The memory that you dynamically allocate for the CNums which the vector is holding pointers to is never released. A vector will not automagically delete this memory.
You are going to have to loop through the vector manually deleting it's the pointers.
You are going to have to loop through the vector manually deleting it's the pointers.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement