当我在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;
}
Run Code Online (Sandbox Code Playgroud)
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,这与长的字节数相匹配.有谁知道为什么会这样?
我在代码中输入了一个拼写错误&a-&c,但这确实与我的问题无关.我的问题是,为什么从变量a的地址到变量b的地址只有2个字节的差异,当long为8个字节长时,我希望看到8的差异?
指针算法基于它指向的类型的大小而不是以字节为单位,这个Pointer Arithmetic的参考很好地涵盖了这个主题,你也有一个错字:
(&a-&c)
Run Code Online (Sandbox Code Playgroud)
你实际上减去c从a.
这也是因为如果指针指向相同的数组指针减法只被定义,见未定义的行为6.5.6/9从C11 draft standard:
[...]当减去两个指针时,两个指针都指向同一个数组对象的元素,或者指向数组对象的最后一个元素的元素; [...]
部分6.5.6/8也是相关的:
[...]如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出; 否则,行为未定义.[...]
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |