Search code examples
cuint8tuint8arraychararray

Is cast from uint8_t* to char* acceptable


Concerning this question

Convert from uint8_t * to char * in C

The suggestion was simply to cast with (char*). Why is this acceptable in this context? Or did the responder just take the question literally?

Casting unsigned (depending on the implementation) to signed feels dubious.


Solution

  • In C, it is allowed to access a variable of a given type through a pointer to the signed or unsigned version of that that type.

    This is specified in section 6.5p7 of the C standard:

    An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

    • a type compatible with the effective type of the object,
    • a qualified version of a type compatible with the effective type of the object,
    • a type that is the signed or unsigned type corresponding to the effective type of the object,
    • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
    • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
    • a character type.

    A uint8_t is an alias for an unsigned char (at least, on systems where CHAR_BIT is 8), so it is allowed to convert an uint8_t * to a char * and subsequently dereference the resulting pointer.

    Note also that, per the last bullet point above, using a pointer any character type is allowed to access any kind of object.