Jump to content
  • Advertisement
Sign in to follow this  
Sfpiano

Pointer and reference to same object

This topic is 4498 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
Advertisement
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
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!