I get a compiler "warning: return discards qualifiers from pointer target type" from my function below.
unsigned char* getBeginning(const unsigned char * Packet)
{
return Packet+3;
}
I have researched this on SO and other places, and it appears the compiler is complaining that although I take in a const pointer, I am returning a non-const pointer.
What I am trying to accomplish is:
1) I want to let the users know that I will not change any of their data in this function, hence the const.
2) However, later functions will use the pointer returned here to make changes, so I don't want to make my return type const as well.
Is there a better way to do this where I don't get a warning? I'm still learning C.
C does not have an implicit conversion from const-qualified pointer types to non-const-qualified ones, so you should add an explicit one, i.e. a cast. Then the warning will go away:
unsigned char* getBeginning(const unsigned char * Packet)
{
return (unsigned char *)Packet+3;
}
Just beware that this function is then mildly "dangerous" as it can hide the dropping of const qualification. But it's no more dangerous than things like strchr
in the standard library which do the same. The behavior is perfectly well-defined as long as you refrain from attempting to modify a const-qualified object via the returned pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With