鱼C论坛

 找回密码
 立即注册
查看: 2866|回复: 4

为什么会出错呢?

[复制链接]
发表于 2014-7-26 08:06:02 | 显示全部楼层 |阅读模式
10鱼币
本帖最后由 拈花小仙 于 2014-7-26 11:34 编辑

#include <Windows.h>
#include <iostream>
int main()
{
    LPWSTR szString = TEXT("hello");
    TCHAR  lpString[10];
    MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
    CopyMemory(lpString,szString,lstrlen(szString)+1);
    MessageBox(NULL,lpString,TEXT("CHAR"),MB_OK);

    return 0;
}

最佳答案

查看完整内容

没有发出错误提示。不知道我们编译出现的错误是否一致首先我项目属性设置的是使用ASCII字符集 LPWSTR szString = TEXT("hello"); error C2440: 'initializing' : cannot convert from 'char [6]' to 'unsigned short *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 类型不一致 定义的是宽字符的变量。项目属性设置的是使用ASCII字符集,TEXT因 ...
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-7-26 08:06:03 | 显示全部楼层
没有发出错误提示。不知道我们编译出现的错误是否一致首先我项目属性设置的是使用ASCII字符集
LPWSTR szString = TEXT("hello");
error C2440: 'initializing' : cannot convert from 'char [6]' to 'unsigned short *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast


类型不一致
定义的是宽字符的变量。项目属性设置的是使用ASCII字符集,TEXT因此会把hello转换成ASCII的形式。于是无法赋值
修改成LPWSTR szString = L"hello";把hello转换成宽字符。或者把项目属性设置为使用UNICODE字符集,这里选择前者



MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
error C2664: 'MessageBoxA' : cannot convert parameter 2 from 'unsigned short *' to 'const char *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

同样的项目属性设置的是使用ASCII字符集,MessageBox=MessageBoxA,也就是使用ASCII字符串作为参数
这里却用了szString宽字符
索性干脆这样改MessageBoxW(NULL,szString,L"LPSTR",MB_OK);


CopyMemory(lpString,szString,lstrlen(szString)+1);
error C2664: 'lstrlenA' : cannot convert parameter 1 from 'unsigned short *' to 'const char *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast


lstrlen因为项目属性设置的是使用ASCII字符集,所以lstrlen=lstrlenA无法获取szString大小,那么
CopyMemory(lpString,szString,lstrlenW(szString)+1);


不过上面几乎是打补丁式的做法。干脆这样
#include <Windows.h>
#include <iostream>
int main()
{
    LPSTR szString = "hello";//直接改
    TCHAR  lpString[10];
    MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
    CopyMemory(lpString,szString,lstrlen(szString)+1);
    MessageBox(NULL,lpString,TEXT("CHAR"),MB_OK);
        
    return 0;
}


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-7-26 11:04:25 | 显示全部楼层
力挺小仙儿!
CopyMemory(lpString,szString,lstrlen(szString)+1);//这句有问题。
//因为是Unicode码,所占字节比Ascii大一倍。所以(lstrlen(szString)+1)*2就好啦
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-7-26 11:32:12 | 显示全部楼层
学些了 看看
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-8-23 10:17:06 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-21 13:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表