How can one portably perform pointer arithmetic with single byte precision?
Keep in mind that:
charis not 1 byte on all platformssizeof(void) == 1is only available as an extension in GCC- While some platforms may have pointer deref pointer alignment restrictions, arithmetic may still require a finer granularity than the size of the smallest fundamental POD type
Your assumption is flawed –
sizeof(char)is defined to be 1 everywhere.From the C99 standard (TC3), in section 6.5.3.4 (“The sizeof operator”):
(paragraph 2)
(paragraph 3)
When these are taken together, it becomes clear that in C, whatever size a char is, that size is a “byte” (even if that’s more than 8 bits, on some given platform).
A
charis therefore the smallest addressable type. If you need to address in units smaller than achar, your only choice is to read acharat a time and use bitwise operators to mask out the parts of thecharthat you want.