Reputation: 1940
I'm a bit rusty with C++ so I'm looking for help with a string pointer question.
First, let's consider some pointer basics with an integer:
void SetBob(int* pBob)
{
*pBob = 5;
}
int main(int argc, _TCHAR* argv[])
{
int bob = 0;
SetBob(&bob);
}
When run, main() creates an integer and passes its address to SetBob. In SetBob, the value (at the address pointed to by pBob) is set to 5. When SetBob returns, bob has a value of 5.
Now, let's consider a string constant:
typedef wchar_t WCHAR;
typedef const WCHAR *PCWSTR;
void SetBob(PCWSTR* bob)
{
*bob = L"Done";
}
int main(int argc, _TCHAR* argv[])
{
PCWSTR bob = L"";
SetBob(&bob);
}
When run, main() creates a PCWSTR, pointing to an empty string, and passes it address to SetBob. In SetBob, the PCWSTR pointer now points to a Done string. When SetBob returns, bob has a value of "Done".
My questions are:
Upvotes: 1
Views: 1595
Reputation: 26
For queestion 1, you just give yourself the correct answer.
And for question 2, it is just like question 1. You see, in the SetBob, the program allocates (you can consider it just like "malloc" ) a space for the string "Done", then set bob's pointer to the address of the string. So in this step, the memory belongs to the string is marked as "used", so even when it comes to the end of the function, it will never be destroyed. Only when you use "free", it will always in your memory.
Upvotes: 1