V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
donbe
V2EX  ›  程序员

问个c语言的类型问题。

  •  
  •   donbe · 2012-04-30 22:41:39 +08:00 · 3372 次点击
    这是一个创建于 4378 天前的主题,其中的信息可能已经有所发展或是发生改变。
    什么时候应该用 unsigned char * ?
    对于一字符串来说 char * 不是更好吗?
    是不是 unsigned char * 表示的不一定是字符串?
    强制转换 unsigned char * 和 char * 会不会带来什么隐患?
    7 条回复    1970-01-01 08:00:00 +08:00
    xupefei
        1
    xupefei  
       2012-04-30 22:47:17 +08:00   ❤️ 1
    一般来说不会有什么问题,不过当你尝试把其中一个字符当做数值来比较时,char可能会出现负数

    另外,根据编译器的不同,char可能被解释为 signed 或 unsigned ,那么当被解释为前者时,你的字符串就出现负数,就出问题了……
    xupefei
        2
    xupefei  
       2012-04-30 22:49:24 +08:00
    这个问题给忘了:
    > 什么时候应该用 unsigned char * ?
    如果你是在定义字符串,任何时候都应该表明 unsigned
    ototsuyume
        3
    ototsuyume  
       2012-04-30 22:51:25 +08:00   ❤️ 1
    什么时候应该用 unsigned char * ?
    二进制数据流

    对于一字符串来说 char * 不是更好吗?


    是不是 unsigned char * 表示的不一定是字符串?


    强制转换 unsigned char * 和 char * 会不会带来什么隐患?
    一般来说不会,但还是尽量别这样干,难免会有例外情况
    simy
        4
    simy  
       2012-04-30 23:45:53 +08:00
    unsigned char我还用来当整数用的。。好吧,忽略我。。
    Hyperion
        5
    Hyperion  
       2012-05-01 00:46:38 +08:00   ❤️ 1
    都一样用就是了, 但是...

    char test[] = {177, 161, '\0'};
    printf("%s %d%d", test, (int)test[0], (int)test[1]);

    unsigned char test[] = {177, 161, '\0'};
    printf("%s %d%d", test, (int)test[0], (int)test[1]);

    -_- 不做解释...
    xuefei2062
        6
    xuefei2062  
       2012-05-01 01:02:01 +08:00
    char有可能是unsigned char,也有可能是signed char,根据系统实现而不同,所以要移植性还是加unsigned或者signed,至于用什么,看你需求
    donbe
        7
    donbe  
    OP
       2012-05-01 02:08:47 +08:00
    v2ex很给力啊,得到这么多回答, 基本明白了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5402 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:01 · PVG 17:01 · LAX 02:01 · JFK 05:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.