Jump to content
  • Advertisement
Sign in to follow this  

[SOLVED]A problem related to vectorpointer

This topic is 4216 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 {
	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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!