3 ms·
The other widespread use of char pointers is when you need to perform pointer arithmetic over a buffer (without any dereferencing) in steps of 1 (as sizeof(char
by bluetomcat 11y ago
The other widespread use of char pointers is when you need to perform pointer arithmetic over a buffer (without any dereferencing) in steps of 1 (as sizeof(char) == 1).
Void pointers do not allow pointer arithmetic (GCC allows it as an extension).
- gvb 11y agoHe covers that in the next section "Signedness" and more thoroughly in "System-Dependent Types" where he recommands (properly) using uintptr_t and intptr_t: The correct type for pointer math is uintptr_t defined in <stddef.h>.
- bluetomcat 11y agoCorrect me if I'm wrong, but in my understanding, the primary purpose of uintptr_t is to type-pun a pointer into a compatible integer, inspect/modify the bits of the integer and then cast it back to a pointer of the same type. I don't feel like it's the right type for simple pointer arithmetic.
- _kst_ 11y agoYou're right, using uintptr_t for pointer arithmetic is a bad idea. I've worked on systems (Cray vector machines) where converting a pointer to an integer type, performing arithmetic on the integer, and converting back to a pointer could yield meaningless results. (Hardware addresses were 64-bit addresses of 64-bit words; byte pointers were implemented by storing a 3-bit offset in the high-order bits of the pointer.) Pointer arithmetic works. It causes undefined behavior if it goes outside the address range of the enclosing object, but in those cases converting to uintptr_t and performing arithmetic will give you garbage results anyway.
- _kst_ 11y agoIf you want to access a buffer as raw bytes (which may or may not be octets), use `unsigned char`. Plain `char` may be either signed or unsigned, depending on the implementation.