Home > Enterprise >  Can I cast a pointer to char?
Can I cast a pointer to char?

Time:11-18

Can I cast void* to char[], or is this illegal? I just want to take a look at the bits. I'm aware of intptr_t, but I would rather not use a typedef that may or may not exist on a given platform.

CodePudding user response:

Can I cast a pointer to char?

Yes, but that is only useful in esoteric circumstances, such as checking the low bits to see the alignment.

Can I cast void* to char[], or is this illegal?

Casting to char [] violates the constraint for the cast operator in C 2018 6.5.4 2:

Unless the type name specifies a void type, the type name shall specify atomic, qualified, or unqualified scalar type, and the operand shall have scalar type.

char [] is not any of those scalar types.

You can cast to char *, but that will not give you the bytes of the pointer; it will give you the pointer as a pointer to char.

I'm aware of intptr_t, but I would rather not use a typedef that may or may not exist on a given platform.

uintptr_t is generally preferable to intptr_t, to avoid complications caused by the sign. There are few C implementations in which it would not exist.

However, there could be some. For that, you can convert not the pointer, but the address of the pointer to unsigned char *. That will give you a new pointer to the bytes of the pointer, and then you can use that to examine those bytes. Again, prefer the unsigned type, unsigned char *, to avoid complications from signedness.

  • Related