Raz
Raz

Reputation: 499

How do I convert a `CString` into a `CHAR *`?

I have the following c++ code:

#include "stdafx.h"
#include <atlstr.h>

int _tmain(int argc, _TCHAR* argv[])
{
    CString OFST_PATH;
    TCHAR DIR_PATH[MAX_PATH];

    GetCurrentDirectory(MAX_PATH, DIR_PATH);

    OFST_PATH.Format(DIR_PATH);

    CHAR *pOFST_PATH = (LPSTR)(LPCTSTR)OFST_PATH;

    return 0;
}

I want to understand why the value of pOFST_PATH in the end of the program is "c"? what did (LPSTR)(LPCTSTR) casting of variable OFST_PATH did to the whole path that was written in there?

As you can see in the following window, when debuging the variables values are:

enter image description here

Upvotes: 1

Views: 10925

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

CString and LPCTSTR are both based on TCHAR, which is wchar_t when UNICODE is defined (which it is, in your case, as I can tell by the value of argv in your debugger). When you do this:

(LPCTSTR)OFST_PATH

That works okay, because CString has a conversion operator to LPCTSTR. But with UNICODE defined, LPCTSTR is LPCWSTR, a.k.a. wchar_t const*. It points to an array of utf16 characters. The first character in that array is L'c' (that's the wide character version of 'c'). The bytes of L'c' look like this in memory: 0x63 0x00. That's the ASCII code for the letter 'c', followed by a zero. So, when you convert your CString to LPCTSTR, that's valid, however, your next conversion:

(LPSTR)(LPCTSTR)OFST_PATH

That's not valid. LPSTR is char*, so you are treating a wchar_t const* as if it's a char*. Well your debugger assumes that when it sees a char*, it is looking at a null terminated narrow character string. And if you remember from above what the value of the bytes of the first character were, it is the ASCII value for the letter 'c', followed by a zero. So the debugger sees this as a null terminated string consisting of just the letter 'c'.

The moral of the story is, don't use c-style casts if you don't understand what they do, and whether they are appropriate.

Upvotes: 10

Related Questions