可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I use strlen()
call all over my project, until now I compiled my project without -Wall
compiler option. But when I start using -Wall
I face so many compiler warning. 80% are the strlen char * vs const char * warning.
I am aware of type casting all strlen()
calls. Is there any other way that I can suppress the following warning?
./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 *'`
回答1:
strlen
takes a const char*
as its input.
Unfortunately the C standard states that signedness of char
is down to the compiler and platform. Many programmers therefore opt to set the signedness of char
explicitly using signed char
or unsigned char
.
But doing that will cause warnings to be emitted if char*
has the other sign convention to what you expect.
Luckily in the context of strlen
, taking a C-style cast is safe: use strlen((const char*)...);
回答2:
There's always the option to do :
inline size_t u_strlen(unsigned char * array) { return strlen((const char*)array); }
This way you don`t have to add a conversion everywhere in your code.
Although the question remains, why are you using unsigned char? I suppose it`s a byte array for data packets over networking, in that case you should take care of the length in the protocol anyways.
回答3:
It is not a matter if char*
vs const char*
, that is not the problem being reported (because it is not a problem). The problem is the fact that you are using unsigned char*
. Whether of not a plain char
is signed or unsigned is implementation dependent; so on some platforms unsigned char*
will be teh saem as char*
and on others it won't.
The best solution is ensure type agreement by not qualifying your strings and string pointers as unsigned
; it almost certainly serves no useful purpose. For strings and characters the distinction between signed and unsigned is irrelevant - that is only of interest when performing arithmetic and using char
as a "small integer".
Most compilers support a command line switch to specify the default signedness of char
; however I would not recommend that as a solution, nor would I recommend casting; correct type agreement should always be your first choice.