问题描述
如何以单字节精度可移植地执行指针算术?
How can one portably perform pointer arithmetic with single byte precision?
请记住:
-
char
在所有平台上不是1个字节 -
= 1
只能作为GCC中的扩展名使用 - 虽然某些平台可能有指针deref指针对齐限制,但算术可能仍需要比最小的基本POD类型
char
is not 1 byte on all platformssizeof(void) == 1
is 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.
从,在第6.5.3.4节(运算符的大小 ):
From the C99 standard (TC3), in section 6.5.3.4 ("The sizeof operator"):
(第2段)
(第3段)
,很明显在C中,无论字符是什么大小,该大小是一个字节(即使在一些给定的平台上超过8位)。
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
char
因此是最小的可寻址类型。如果您需要以小于 char
的单位进行编址,则您唯一的选择是一次读取一个 char
使用按位运算符来隐藏所需的 char
部分。
A
char
is therefore the smallest addressable type. If you need to address in units smaller than a char
, your only choice is to read a char
at a time and use bitwise operators to mask out the parts of the char
that you want.
这篇关于字节精度指针算术在C当sizeof(char)!= 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!