Sign in to follow this  

Pointer and reference to same object

This topic is 4282 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

Say I have a function: copy(myStruct* a, myStruct b) { erase(a); init(a); a->one = b.one; a->two = b.two; ... } How can I make this work: myStruct a; copy(&a, a); Because right now when I try it, when it erases the pointer to 'a', the reference value 'b' also gets changed.

Share this post


Link to post
Share on other sites
You might try checking to see if a != &b. If they aren't equal, then do the copy. Otherwise, skip it. However, I'm not sure if grabbing the address of b is good enough. You might need to declare b to be volatile as well. Personally, if I were to do this, I'd just switch b to be a pointer as well.

Share this post


Link to post
Share on other sites
Simply grabbing &b will not work, because b is not a reference type. It is already a copy of the original object, so it will have a unique address.

Assuming you're using C, the best solution I'm aware of would be to pass b in as a pointer as well. But I'm not exactly an expert C programmer.

If you aren't using C, then there are probably better solutions all together. In C++, for instance, you'll want to make use of copy constructors and assignment operators. Google around and you should find examples. You can also use references, so that checking &b inside the function will work as intended.

CM

Share this post


Link to post
Share on other sites

This topic is 4282 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.

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