Sign in to follow this  
TimChan

[SOLVED]A problem related to vectorpointer

Recommended Posts

The output is something like below: original address: 0x3d3770 2 new address(?): 0x289d720 Plus an error message from the system. And the source:
#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;
}



How come the address changes after the return of the function find_num?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Thank you.

The problem is solved by simply change "find_num(int _n, CNum* _pointer)" to "find_num(int _n, CNum*& _pointer)".

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this