student1的名字打印正确" alice",但student2的名字打印在"奇怪的字符"。
char * student;
student = "alice";
printf("student1 : %s\n", student);
CString student2;
student2 = "alice";
student = (char *)( LPCSTR )student2;
printf("student2:%s\n", student);
为什么用"(char *)(LPCSTR)" ,它会返回奇怪的角色吗?
答案 0 :(得分:0)
首先,这个程序对我有用。
但是,这并不意味着它是正确的
对于MBCS,通常使用_T
宏来确保正确声明字符串。
以下是我对代码的简单重写:
#include "stdafx.h"
#include "atlstr.h"
int _tmain(int argc, _TCHAR* argv[])
{
LPCSTR student = _T("alice"); // Use the provided LPCSTR type instead of char*.
printf("student1 : %s\n", student);
CString student2(_T("alice")); // Initialize a CString with the _T macro
student = (LPCSTR)student2; // LPCSTR is typedef to char*.
// So you effectively had (char*)(char*)student2;
// TypeCasting something twice to the same type is stupid.
printf("student2:%s\n", student);
return 0;
}
<强> 输出 强>
student1 : alice
student2:alice