memcpy CString to char *

时间:2013-10-30 14:06:05

标签: c++ memcpy

我正在尝试使用CStringchar*复制到memcpy(),我很难做到这一点。实际上,只复制第一个字符。这是我的代码:

CString str = _T("something");
char* buff  = new char();

memcpy(buff, str, str.GetLength() + 1);

在此之后,buff包含的所有内容都是字母s

3 个答案:

答案 0 :(得分:6)

您可能正在混合使用ASCII和Unicode字符串。如果使用Unicode设置进行编译,则CString存储一个Unicode字符串(每个字符两个字节,在您的情况下,每个第二个字节为0,因此看起来像一个ASCII字符串终止符。)

如果你想要所有的ASCII:

CStringA str = "something";
char* buff = new char[str.GetLength()+1];
memcpy(buff, (LPCSTR)str, str.GetLength() + 1);

如果您想要所有Unicode:

CStringW str = L"something";
wchar_t* buff = new wchar_t[str.GetLength()+1];
memcpy(buff, (LPCWSTR)str, sizeof(wchar_t)*(str.GetLength() + 1));

如果您希望它同时适用于这两种设置:

CString str = _T("something");
TCHAR* buff = new TCHAR[str.GetLength()+1];
memcpy(buff, (LPCTSTR)str, sizeof(TCHAR) * (str.GetLength() + 1));

如果要将Unicode字符串转换为ASCII字符串:

CString str = _T("something");
char* buff = new char[str.GetLength()+1];
memcpy(buff, (LPCSTR)CT2A(str), str.GetLength() + 1);

请同时识别从str到LPCSTR,LPCWSTR或LPCTSTR的转换以及更正的缓冲区分配(需要多个字符,而不仅仅是一个)。

另外,我不太确定这是否真的是你需要的。例如,strdup看起来比new + memcpy简单得多。

答案 1 :(得分:3)

您只分配了内存来保存char变量。要做你想做的事,你需要分配足够的内存来保存完整的字符串。

CString str = _T("something");
LPTSTR buff = new TCHAR[(str.GetLength()+1) * sizeof(TCHAR)]; //allocate sufficient memory
memcpy(buff, str, str.GetLength() + 1);

答案 2 :(得分:0)

你是

  1. 只分配一个char,除非CString为空,否则不够,
  2. 复制CString实例而不是它代表的字符串。
  3. 尝试

    CString str = _T("something");
    int size = str.GetLength() + 1;
    char* buff = new char[size];
    memcpy(buff, str.GetBuffer(), size);