Pointer and reference to same object
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.
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.
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
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement