Warning generated due wrong strcmp parameter handl

2019-07-15 00:30发布

问题:

So I have an

unsigned char * pMyPtr 

assigned to something.

Then I want to compare this to an arbitrary string with

strcmp(const char* , const char* )

But when I do that, clang compiler tells me

warning: passing (aka 'unsigned char *') to parameter of type 'const char *' converts between pointers to integer types with different sign

How do I remove this warning?

回答1:

With all the comments to the question, I feel like I'm missing something.

I know that casts are unfashionable, but isn't the following a simple workaround?

strcmp((const char*) pMyPtr , whatever_is_being_compared)


回答2:

It isn't even unsigned. Behind it, is a struct.

This means that you cannot use strcmp here. You can use strcmp when the input data are null-terminated strings. That's not the case when the input data are structs. Perhaps you should consider memcmp instead, or perhaps you need to compare the structs as structs.



回答3:

Clang can't convert from unsigned char* to const char*. That because unsigned char* is different then char*. By adding unsiged you make the range of char 0to255 instead of -127to127.

On the line where strcmp goes, you can typecast the unsigned char value with (const char*) which will work, because there it will be threated as a const char*. instead of unsigned char



回答4:

If you feel that warning does not have any side effect. you can ignore the warning like this:

#pragma warning( disable : 4507 34 )


标签: c++ c clang