字节precision指针运算在c当的sizeof(字符)!= 1 [英] Byte precision pointer arithmetic in C when sizeof(char) != 1
问题描述
如何可以在一个可移植的单字节precision执行指针运算?
How can one portably perform pointer arithmetic with single byte precision?
记住:
-
字符
不是在所有平台上1个字节 -
的sizeof(无效)== 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操作符产生的大小
(字节)的操作数,这可能
是当然pression或
一个类型的括号中的名字。
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型或签名
CHAR,(或合格版本
物)的结果为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).
A 字符
因此最小的可寻址类型。如果您需要在单位比小字符
,你唯一的选择是读,以解决字符
的时间和使用位运算符来屏蔽掉的部分字符
你想要的。
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.
这篇关于字节precision指针运算在c当的sizeof(字符)!= 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!