What's the correct way to add 1 byte to a pointer in C/C++?

前端 未结 6 559
忘了有多久
忘了有多久 2021-01-18 08:53

I\'m using this code to move pointer by 1 byte now, but I\'m feeling something unclear..

int* a = (int*)malloc(sizeof(int));
void* b = ((char*)a)+1;   
         


        
6条回答
  •  天涯浪人
    2021-01-18 09:18

    In C99, you have the stdint.h header, which contains int8_t and uint8_t types, which are guaranteed to be 8 bits (and generally are just typedefs for char). Beyond this, there is no real language level support for bytes in C or C++, in fact the standard goes out of its way to say that sizeof for example is in units of char (and not bytes). There is also the CHAR_BIT macro which tells you the number of bits in a byte, on some platforms char was 9bits for example. Of course I'm assuming by byte you mean octet.

提交回复
热议问题