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

前端 未结 7 1260
悲哀的现实
悲哀的现实 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:33

    Cast the pointer to a uintptr_t. This will be an unsigned integer that is the size of a pointer. Now do your arithmetic on it, then cast the result back to a pointer of the type you want to dereference.

    (Note that intptr_t is signed, which is usually NOT what you want! It's safer to stick to uintptr_t unless you have a good reason not to!)

    0 讨论(0)
提交回复
热议问题