Byte precision pointer arithmetic in C when sizeof(char) != 1

前端 未结 7 1274
悲哀的现实
悲哀的现实 2020-12-11 13:07

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

Keep in mind that:

  • char is not 1 byte on all platforms
7条回答
  •  离开以前
    2020-12-11 13:13

    sizeof(char) is guaranteed to be 1 by the C standard. Even if char uses 9 bits or more.

    So you can do:

    type *pt;
    unsigned char *pc = (unsigned char *)pt;
    

    And use pc for arithmetic. Assigning pc to pt by using the cast above is undefined behavior by the C standard though.

    If char is more than 8-bits wide, you can't do byte-precision pointer arithmetic in portable (ANSI/ISO) C. Here, by byte, I mean 8 bits. This is because the fundamental type itself is bigger than 8 bits.

提交回复
热议问题