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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.