C Pointer Arithmetic sizeof(struct)

前端 未结 4 599
既然无缘
既然无缘 2021-01-05 07:19

Here is the code in question

#include 

struct test {
    unsigned char t;
    unsigned short u;
    unsigned char v;
};


int main ()
{
    s         


        
4条回答
  •  清歌不尽
    2021-01-05 07:55

    When you do pointer arithmetic like this, you move forward or back by that number of elements, as though that variable were in an array. So you really want to just use a + 1 and a - 1, which should advance by 6 bytes each time.

    IMPORTANT: Keep in mind that the compiler can add padding in your struct to help with alignment. Don't just assume that because you have two one-byte chars and a two-byte short that your struct will be 4 bytes in size---this isn't the case here. (In fact, don't assume that you know the size of char or short; I've seen 2-byte chars before).

提交回复
热议问题