1

Hello I’m new to c++ and I’m trying to figure out how to use pointers to change the same object.

If I have a vector of pointers for example

std::vector<myclass*> top;

and lets say the top[0] = NULL I want to use another pointer to change it

myclass* other = top[0];
other = new myclass();

So that when I access top[0] it will be pointed to the new object created? Sorry a little confusing but that’s the idea.

3
  • top[0] = new myclass? Commented Feb 7, 2020 at 4:49
  • I’m sorry I edited what I was trying to mean. Commented Feb 7, 2020 at 4:51
  • In C++ you may better use reference, not pointer in this case. Commented Feb 7, 2020 at 5:00

2 Answers 2

2

If, for example, you had a vector of int:

std::vector<int> vec(10);

and then did something like

int other = vec[0];
other = 5;

I think most people would understand that the assignment other = 5; would change the value of the variable other only, not the value of vec[0].

Now lets take your code:

myclass* other = top[0];
other = new myclass();

It's exactly the same thing here: The assignment other = new myclass(); only changes the variable other and where it points, it doesn't change top[0].

What I think you want is to use other as a reference to the value in top[0], which you can do by using references:

myclass*& other = top[0];
other = new myclass();

Now other will be a reference to the value in top[0], so the assignment will change top[0].

And for completeness sake, and keeping with the pointer-to-pointer thing in the title, you could of course solve it through pointers to pointers:

myclass** other = &top[0];
*other = new myclass();

With the above other will be a pointer to top[0], and you need to use the dereference operator * (as in *other) in the assignment to change the value at top[0]. I really recommend the references though.

Sign up to request clarification or add additional context in comments.

Comments

0

You've got things a bit backward:

myclass *other = new myclass();
top[0] = other;

EDIT:

You need to take the address of the vector element:

std::vector<myclass*> top(5);
myclass *other = new myclass();
other->x = 4;
top[0] = other;
printf("top[0].x=%d\n", top[0]->x);
myclass **p = &top[0];
(*p)->x = 5;
printf("top[0].x=%d\n", top[0]->x);

Output:

top[0].x=4
top[0].x=5

1 Comment

No I’m sorry i edited up top, i need two pointers that would change value of what it’s pointing to?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.