passing argument 1 of 'strlen' differ in signedness

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!