Link to home
Start Free TrialLog in
Avatar of PMH4514
PMH4514

asked on

Copy CString to TCHAR*

How do I copy the value of a CString into a TCHAR* ??

Note, a UNICODE build.

For example:

TCHAR* szTest = NULL;                                  // watcher shows  0x00000000  ""
CString sTest = _T("hello world");                   // watcher shows  0x0d27dff8 {"hello world"}
szTest = sTest.GetBuffer(sTest.GetLength());   // watcher shows 0x0ce86ed4 "hello world"  looks like a copy to me!?
sTest.Empty();

after sTest.Empty() the watcher for sTest shows 0x0d27dff8 {""} but now szTest in the watcher shows 0x0ce86ed4 "???????????????????????????????????????"

what am I doing wrong?

thanks!



Avatar of Axter
Axter
Flag of United States of America image

>>what am I doing wrong?

You need to create space for the data.

TCHAR* szTest = NULL;                                  
CString sTest = _T("hello world");                  
szTest = new TCHAR[sTest.GetLength()];

strcpy(szTest, sTest );

//After you're done with szTest, make sure to delete it

delete [] szTest;
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PMH4514
PMH4514

ASKER

ahh yes of course, it's a pointer.. I'm so used to CString..

or:
    _tcsncpy_s(szTest,_sTest.GetLength(),sTest,_TRUNCATE);

to be safer.