字节精度指针算术在C当sizeof(char)!= 1 [英] Byte precision pointer arithmetic in C when sizeof(char) != 1

查看:262
本文介绍了字节精度指针算术在C当sizeof(char)!= 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以单字节精度可移植地执行指针算术?

How can one portably perform pointer arithmetic with single byte precision?

请记住:


  • char 在所有平台上不是1个字节

  • = 1 只能作为GCC中的扩展名使用

  • 虽然某些平台可能有指针deref指针对齐限制,但算术可能仍需要比最小的基本POD类型

  • char is not 1 byte on all platforms
  • sizeof(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.

www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdfrel =nofollow noreferrer> C99标准(TC3),在第6.5.3.4节(运算符的大小 ):

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或signed
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中,无论字符是什么大小,该大小是一个字节(即使在一些给定的平台上超过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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆