问题
I'm trying to pass a string to a function:
void PassString(unsigned char * value)
{
// ...
}
int main(void)
{
while(1)
{
PassString("TEST");
}
}
I'm getting warning: (359) illegal conversion between pointer types.
回答1:
Short answer:
String literals such as "TEST"
are of type char[]
in C.
So change the function to accept char*
. Or cast the argument to unsigned char*
, even though that's a less clean solution.
Some history behind char
:
The C type system is a bit dysfunctional when it comes to the character types. In the dawn of time when dinosaurs walked the earth, it wasn't specified if char
should be signed
or unsigned
per default.
signed
made sense because that makes char
consistent with the larger integer types. unsigned
also made sense, because there exist no character symbol tables with negative indices.
Upon language standardization, there already existed various compilers that gave char
different signedness. So it was decided that the signedness of char
should be implementation-defined. That is: each compiler decides.
For the same reason, the types char
, signed char
and unsigned char
were stated to be 3 different types. This means that you cannot implicitly convert between pointers to these types. Instead you need to use an explicit conversion by casting.
Only the character types behave this weird. If you take for example int
and signed int
they are always compatible and int
is always signed.
This is a known shortcoming of the C language. The types from the stdint.h
library are therefore preferred over "raw" character types.
Best practice using character types:
- Use the type
char
if you are dealing with (up to 8 bit) text strings, and only then. - Use the type
unsigned char
oruint8_t
if you are dealing with raw binary data or doing type punning etc. - Use
signed char
orint8_t
if you are doing signed 8 bit integer arithmetic. - Use
unsigned char
oruint8_t
if you are doing unsigned 8 bit integer arithmetic. - There is never any danger converting between the various character types unless signedness matters.
- But... be careful when doing any form of arithmetic on these types, since it comes with many pitfalls. See Implicit type promotion rules.
回答2:
The string literal being passed is of type char []
but the argument is given as unsigned char *
.
So change the type of the argument to char[]
.
来源:https://stackoverflow.com/questions/53207195/warning-359-when-passing-string-to-char