这个设计决定是不幸的,但植根于 40 年前做出的另一个不幸的选择:允许char潜在地默认签名,这与 的行为不一致getchar(),strcmp() ...
您可以使用内联函数通过单个隐藏强制转换从char *到unsigned char *,反之亦然,并在传递参数时使用这些:
static inline unsigned char *c2uc(char *s) { return (unsigned char*)s; }
static inline char *uc2c(unsigned char *s) { return (char*)s; }
Run Code Online (Sandbox Code Playgroud)
这些包装器比基本类型转换更安全,因为它们只能应用于一种类型并转换为unsigned对应的类型。常规强制转换是有问题的,因为它们可以应用于任何类型并隐藏类型转换错误。 static inline编译器在没有运行时成本的情况下扩展函数。