当我在
Xcode中的64位Intel中编译下面的代码时,我得到了这个输出.
#include<stdio.h> #include<limits.h> int main(void) { /* declare some integer variables */ long a = LONG_MAX; long b = 2L; long c = 3L; /* declare some floating-point variables */ double d = 4.0; double e = 5.0; double f = 6.0; printf("A variable of type long occupies %d bytes.",sizeof(long)); printf("\nHere are the addresses of some variables of type long:"); printf("\nThe address of a is: %p The address of b is: %p",&a,&b); printf("\nThe address of c is: %p",&c); printf("\nThe address of a-b is: %ld\nvalue of a is %ld\nValue of b is %ld\nsize of pointer %ld ",(&a-&c),a,b,sizeof(&a)); printf("\n\nA variable of type double occupies %d bytes.",sizeof(double)); printf("\nHere are the addresses of some variables of type double:"); printf("\nThe address of d is: %p The address of e is: %p",&d,&e); printf("\nThe address of f is: %p\n",&f); printf("\n size long - %d",sizeof(a)); return 0; }
A variable of type long occupies 8 bytes. Here are the addresses of some variables of type long: The address of a is: 0x7fff5fbff880 The address of b is: 0x7fff5fbff878 The address of c is: 0x7fff5fbff870 The address of a-b is: 2 value of a is 9223372036854775807 Value of b is 2 size of pointer 8 A variable of type double occupies 8 bytes. Here are the addresses of some variables of type double: The address of d is: 0x7fff5fbff868 The address of e is: 0x7fff5fbff860 The address of f is: 0x7fff5fbff858 size long - 8
对我来说奇怪的是a和b的地址之间的差异只有2.我希望它是8,这将与long的字节数相匹配.有谁知道为什么会这样?
我在代码中输入了一个拼写错误& a-& c,但这真的与我的问题无关.我的问题是,为什么从变量a的地址到变量b的地址只有2个字节的差异,当long为8个字节长时,我希望看到8的差异?
解决方法
差异以sizeof(long)为单位.要强制它以字节为单位,你应该先抛出两个指针:
((char *)&a-(char *)&b)
以这种方式,差异以sizeof(char)为单位,即字节数
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。