• 请不要在回答技术问题时复制粘贴 AI 生成的内容
donbe
V2EX  ›  程序员

问个c语言的类型问题。

  •  
  •   donbe · Apr 30, 2012 · 4410 views
    This topic created in 5151 days ago, the information mentioned may be changed or developed.
    什么时候应该用 unsigned char * ?
    对于一字符串来说 char * 不是更好吗?
    是不是 unsigned char * 表示的不一定是字符串?
    强制转换 unsigned char * 和 char * 会不会带来什么隐患?
    7 replies    1970-01-01 08:00:00 +08:00
    xupefei
        1
    xupefei  
       Apr 30, 2012   ❤️ 1
    一般来说不会有什么问题,不过当你尝试把其中一个字符当做数值来比较时,char可能会出现负数

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

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


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


    强制转换 unsigned char * 和 char * 会不会带来什么隐患?
    一般来说不会,但还是尽量别这样干,难免会有例外情况
    simy
        4
    simy  
       Apr 30, 2012
    unsigned char我还用来当整数用的。。好吧,忽略我。。
    Hyperion
        5
    Hyperion  
       May 1, 2012   ❤️ 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  
       May 1, 2012
    char有可能是unsigned char,也有可能是signed char,根据系统实现而不同,所以要移植性还是加unsigned或者signed,至于用什么,看你需求
    donbe
        7
    donbe  
    OP
       May 1, 2012
    v2ex很给力啊,得到这么多回答, 基本明白了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5994 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 01:57 · PVG 09:57 · LAX 18:57 · JFK 21:57
    ♥ Do have faith in what you're doing.