C Pointer Arithmetic sizeof(struct)

前端 未结 4 594
既然无缘
既然无缘 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:46

    The problem is that when you do pointer arithmetic, it increments by a multiple of the size of the datatype.

    So what you're effectively doing is adding by the square of sizeof(struct test).

    Since sizeof(struct test) = 6, you are incrementing the address by 6 * 6 = 36. Hence why you get 0x1024 and 0xfdc instead of 0x1006 and 0xffa. (You also switched the + and -, but that's a small thing.)

    Instead, just do this:

    printf("%x %p %p\n",
           sizeof(struct test),
           a + 1,
           a - 1);
    

提交回复
热议问题