C 指针算术 sizeof(struct) [英] C Pointer Arithmetic sizeof(struct)

查看:53
本文介绍了C 指针算术 sizeof(struct)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有问题的代码

#include <stdio.h>

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


int main ()
{
    struct test  * a = (void *) 0x1000;

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

    return 0;
}

sizeof(struct test) 打印 6,所以我期望看到:

The sizeof(struct test) prints 6, so I would expect to see:

6 0xffa 0x1006

相反,我得到

6 0x1024 0xfdc

上次我检查时,0x24 或 36 不等于 6.它甚至与我能分辨的任何东西都不对齐.我完全不知所措.

Last time I checked, 0x24, or 36, was not equal to 6. It's not even aligned to anything that I can tell. I am at a complete loss.

有人可以向我解释为什么我会得到这些值吗?

Can someone please explain to me why I'm getting these values?

推荐答案

问题在于,当您进行指针运算时,它会增加数据类型大小的倍数.

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

所以你有效地做的是通过 sizeof(struct test) 的平方相加.

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

由于 sizeof(struct test) = 6,您将地址增加 6 * 6 = 36.这就是为什么你得到 0x10240xfdc 而不是 0x10060xffa 的原因.(您还切换了 +-,但这只是小事.)

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.)

相反,只需这样做:

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

这篇关于C 指针算术 sizeof(struct)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆