"uny ternally" <un********@hotmail.com> wrote in message
news:aa*************************@posting.google.co m...
I was experimenting in Visual C++ and ran into the following problem.
I have the struct listed below. I also have a function that passes a
variable of the struct type by reference and set the values. When I
access the struct in the global space after calling the function the
integer value is correcty, however the LPTSTR value is empty. Help.
Below is the code I'm playing with.
Your problem is nothing to do with references. Instead its a
misunderstanding of object scope and pointers. Explaination below.
Thanks.
typedef struct conf
{
LPTSTR entry1;
int entry2;
};
This is not legal C++. You are mixing up C and C++ and getting it wrong for
both. Lose the typedef.
bool GetConf(conf& config)
{
CString value;
A CString is created here.
DWORD dwSize = MAX_PATH;
DWORD val2;
LPTSTR val = value.GetBuffer(1000);
// code setting val and val2
config.entry1 = val2;
config.entry2 = val;
std::cout << "inside: " << config.entry2 << "\n";
You mean entry1.
// config.entry2 dispalys properly here
return TRUE;
That CString is destroyed here.
}
... inside of main
bool returnval;
conf cony;
returnval = GetConf(cony);
std::cout << "outside: " << cony.entry2 << "\n";
\\here cony.entry2 is empty. Note if both cout's are changed from
entry2 to entry they work correctly both inside and outside.
Again you mean entry1.
Now conv.entry1 is a pointer pointing to the internals of a CString object
that has already been destroyed. That's why it is 'empty'. You are lucky
that your program doesn't crash.
I would recommend not useing pointers here (in fact I would recommend that
newbies avoid pointers altogther).
Try this code
struct conf
{
CString entry1;
int entry2;
};
bool GetConf(conf& config)
{
CString value;
DWORD val2;
...
// code setting val and val2
config.entry1 = val2;
config.entry2 = value;
std::cout << "inside: " << config.entry2 << "\n";
// config.entry2 dispalys properly here
return TRUE;
}
No pointers, no problem.
Also I recommend that you drop CString and use the superior and standard C++
string class instead.
john