【发布时间】:2019-12-12 06:00:17
【问题描述】:
我期待下面的代码打印 4(因为浮点数是 4 个字节),但它打印 1。有人能解释一下为什么会这样吗?
#include <stdio.h>
int main()
{
float a[4]={0.0,0.1,0.2,0.3};
printf("%d", &a[1]-&a[0]);
return 0;
}
【问题讨论】:
-
总是在编译时启用编译器警告,你会看到
"warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=] printf("%d", &a[1]-&a[0]);" -
指针算术由指针
type控制。您的类型是float,它是 4 字节。&a[1]-&a[0]之间有多少个 4 字节的值?printf("%ld\n", (&a[1]-&a[0]) * sizeof(float));产生了什么?
标签: c pointers subtraction