What is the use of unsigned char
pointers? I have seen it at many places that pointer is type cast to pointer to unsinged char
Why do we do so?
In C, unsigned char
is the only type guaranteed to have no trapping values, and which guarantees copying will result in an exact bitwise image. (C++ extends this guarantee to char
as well.) For this reason, it is traditionally used for "raw memory" (e.g. the semantics of memcpy
are defined in terms of unsigned char
).
In addition, unsigned integral types in general are used when bitwise operations (&
, |
, >>
etc.) are going to be used. unsigned char
is the smallest unsigned integral type, and may be used when manipulating arrays of small values on which bitwise operations are used. Occasionally, it's also used because one needs the modulo behavior in case of overflow, although this is more frequent with larger types (e.g. when calculating a hash value). Both of these reasons apply to unsigned types in general; unsigned char
will normally only be used for them when there is a need to reduce memory use.