Possible Duplicate:
C++: Passing pointer variable to function
Here is a simplified code snippet which I think shows the problem at hand:
std::wstring *Variable3 = &SomeWStringObject;
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring *Variable1 = NULL;
func(Variable1);
}
void func(std::wstring *Variable2)
{
Variable2 = Variable3;
}
Now, in reality, func is a member of a class, and Variable3 is also a member of that same class. For this simpler example, let’s just assume that Variable3 is some sort of global variable.
Variable3 is a (global variable) pointer to a std::wstring object. I can see in the debugger than it is pointing to the correct string.
What I want to end up with is Variable1 pointing to the same std::wstring object as Variable3.
So I tried passing the address of pointer Variable1 into the function, which I hoped would then set the address Variable3 points to into Variable1.
But this isn’t working. It seems to be set OK, but then when the program leaves func, Variable1 is still a null pointer.
I have tried to be as clear as I can. I hope it is enough. Unfortunately, I cannot use the return value of func for this, as I actually have two other std::wstringstream objects to do the same thing to. Since all are having the same problem, I simplified it down to just one std::wstring object. I have tried lots of other different combinations of & and *, but none have worked.
Thank you very much for any help you can offer.
At the moment you’re copying the value of
Variable1(which is the null pointer value) intofuncand then you’re modifying that copy. So theVariable1outsidefuncis not changed. The immediate solution for people who are a little pointer-prone is to add another level of indirection. Pass a pointer to yourVariable1and then modify it through that. Like so:However, this is not very good style. C++ has reference types that allow you to pass an object into a function without copying it, so that the object inside the function is the same as the object outside. We can use it like so:
Variable2is a reference to a pointer (denoted by the&). It means that when you passVariable1, it is not copied andVariable2refers to precisely the same pointer. ModifyingVariable2will modifyVariable1too.The next question you should ask yourself is “Do I need a pointer to
std::wstringin the first place?” I can’t answer that for you, but often the answer is no.And then the neeext question is why you are passing output through a parameter. This is a very C-ish thing to do (but even they wouldn’t do it in this situation). This is the reason we have return values. Ideally, your code would look like this:
Or potentially you will want to return a reference to
Variable3, in whicih case yourfuncreturn type should bestd::wstring&.