当 sizeof(char) != 1 时 C 中的字节精度指针算术 [英] Byte precision pointer arithmetic in C when sizeof(char) != 1
问题描述
如何以单字节精度便携地执行指针运算?
How can one portably perform pointer arithmetic with single byte precision?
请记住:
char
在所有平台上都不是 1 字节sizeof(void) == 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
推荐答案
您的假设是有缺陷的 - sizeof(char)
被定义 为 1.
Your assumption is flawed - sizeof(char)
is defined to be 1 everywhere.
来自 C99 标准 (TC3),在第 6.5.3.4 节(sizeof 运算符")中:
From the C99 standard (TC3), in section 6.5.3.4 ("The sizeof operator"):
(第 2 段)
sizeof 运算符产生大小(以字节为单位)其操作数,这可能是一个表达式或带括号的类型名称.
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.
(第 3 段)
当应用于具有输入 char、unsigned char 或 signedchar,(或合格的版本其中)结果为 1.
When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.
当将这些放在一起时,很明显在 C 中,无论 char 是什么大小,该大小都是一个字节"(即使在某些给定平台上超过 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).
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.
这篇关于当 sizeof(char) != 1 时 C 中的字节精度指针算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!