我strlen()在我的项目中使用调用,直到现在我编译我的项目没有-Wall编译器选项。但是当我开始使用时,-Wall我遇到了很多编译器警告。80% 是 strlenchar *与const char *警告。
我知道对所有strlen()调用进行类型转换。有没有其他方法可以抑制以下警告?
./Proj.c:3126: warning: pointer targets in passing argument 1 of
'strlen' differ in signedness`
C:/staging/usr/include/string.h:397: note: expected 'const char *' but
argument is of type 'unsigned char *'`
Run Code Online (Sandbox Code Playgroud)
strlen将 aconst char*作为其输入。
不幸的是,C 标准声明的签名取决于char编译器和平台。因此,许多程序员选择设置char显式使用signed charor的签名unsigned char。
但是如果char*有其他你期望的符号约定,这样做会导致发出警告。
幸运的是,在 的上下文中strlen,采用 C 风格的强制转换是安全的:使用strlen((const char*)...);
总有可以做的选择:
inline size_t u_strlen(const unsigned char * array)
{
return strlen((const char*)array);
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必在代码中的任何地方添加转换。
尽管问题仍然存在,但为什么要使用 unsigned char?我认为它是网络数据包的字节数组,在这种情况下,无论如何你都应该注意协议中的长度。