这是我的代码。结构内变量的地址计算
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
struct test
{
unsigned int x;
long int y: 32;
unsigned int z;
};
int main()
{
struct test t;
unsigned int *ptr1 = &t.x;
unsigned int *ptr2 = &t.z;
printf("ptr1 address is %p\n", ptr1);
printf("ptr2 address is %p\n", ptr2);
printf("size: %d", ptr2 - ptr1);
return 0;
}
这是输出:
ptr1 address is 0028FEDC
ptr2 address is 0028FEE4
size: 2
我想我在这里失去了一个点,我输出的认识。我期待输出为4.因为,long int在我的机器上占用4个字节。我得到了x和z的地址之间的区别。但是,不是真实的输出,而不是通过手动减去x和z的地址而获得的输出。如果你看到上面的内容,根据我的计算,28FEE4-28FEDC = 8,但输出是2.谁能告诉我我的计算错在哪里?
如果要在结构中使用32位有符号整数,为什么要使用位域而不是'int32_t'? –
为了得到字节数,你需要按指定类型的大小缩放指针的差别:'ptr2-ptr1' = 2,乘以'sizeof(unsigned int)',这显然是4系统,得到8个字节。 – owacoder
从技术上讲,你对两个指针的减法是* undefined behavior *,因为它们都不指向“对象”。 –