Click to See Complete Forum and Search --> : Passing CString pointers to a function
Shahzad Alam
April 13th, 1999, 06:32 AM
I have made a class with several function. I want one of my function to return several values of type string. So I have to use pointers. I am very uncomfortable with the LPCSTR kind of variable names. Can somebody give me simple example using pointers to return 2 values of CString type.
thankx
Karl
April 13th, 1999, 09:04 AM
Instead of pointers on CString, you may use a CStringArray (or CStringList) passed by reference to your function;
void CMyClass:MyFunction(CStringList &stringList)
{
// empty string List
stringlist.RemoveAll();
// fill string List
stringList.AddTail("string1");
stringList.AddTail("string2");
}
HTH.
K.
Ash to ash and clay to clay, if the enemy doesn't get you, your own folk may.
sally
April 14th, 1999, 03:24 AM
void CThisClass::ThisFunction(CString& p_str1, CString& p_str2)
{
p_str1 = "here we go";
p_str2 = "we go we go";
}
will do it WITHOUT pointers, but with references
Sally
Sally
April 14th, 1999, 03:24 AM
void CThisClass::ThisFunction(CString& p_str1, CString& p_str2)
{
p_str1 = "here we go";
p_str2 = "we go we go";
}
will do it WITHOUT pointers, but with references
Sally
Dave Lorde
April 14th, 1999, 04:42 AM
> Can somebody give me simple example using pointers to return 2 values of CString type
This is the kind of thing you asked for (yuk!):
void GetStrings(CString* pStr1, CString* pStr2)
{
if (pStr1)
*pStr1 = "Replaced existing string 1";
else
pStr1 = new CString("Allocated new string 1");
if (pStr2)
*pStr2 = "Replaced existing string 2";
else
pStr2 = new CString("Allocated new string 2");
}
As you can see, how you handle the CString pointers depends on whether they already point to CStrings or not. If you allocate new CStrings, you must remember to delete them when you've finished with them. If you decide to do it this way (I think it's a big mistake), you should *never* mix heap-based and stack-based CStrings as arguments, and *always* initialize your pointers.
I would strongly recommended you *not* to use CString pointers as arguments. If you pass references instead, the function will be simpler, safer, and clearer:
void GetStrings(CString& str1, CString& str2)
{
str1 = "Replaced existing string 1";
str2 = "Replaced existing string 2";
}
Dave
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.