gpt4 book ai didi

c - 为什么浮点指针的取消引用设置为 int 变量的地址打印为 `0` ?

转载 作者:行者123 更新时间:2023-11-30 19:07:28 25 4
gpt4 key购买 nike

我在使用指针时创建了以下代码 -

#include <stdio.h>
int main()
{
float a=1000;
int *c=&a;
float *d=&a;
printf("\nValue of a is %f",a);
printf("\nValue of a is %f",*c);
printf("\nValue of a is %f",*d);
printf("\nValue of a is %f",*&*c);
printf("\nValue of a is %f\n",*&*d);

int b=2000;
int *e=&b;
float *f=&b;
printf("\nValue of b is %d",b);
printf("\nValue of b is %d",*e);
printf("\nValue of b is %d",*f); //Will produce 0 output
printf("\nValue of b is %d",*&*e);
printf("\nValue of b is %d\n",*&*f); //Will produce 0 output

float g=3000;
float *h=&g;
printf("\nValue of g is %f\n",*h);
}

产生了输出 -

aalpanigrahi@aalpanigrahi-HP-Pavilion-g4-Notebook-PC:~/Desktop/C/Daily programs/pointers$ ./pointer004

Value of a is 1000.000000
Value of a is 1000.000000
Value of a is 1000.000000
Value of a is 1000.000000
Value of a is 1000.000000

Value of b is 2000
Value of b is 2000
Value of b is 0
Value of b is 2000
Value of b is 0

Value of g is 3000.000000

对于第二部分,其中变量 b 已声明为整数*e 和 *f 是指针,其值在 *f 和 *&*f 的情况下 b 打印为 0(如代码所示),但这在上面的情况下有效,其中 变量 a已被声明为 float 。

为什么会出现这种情况?

最佳答案

此问题取决于系统。在某些平台中您将收到 0,而在某些平台中您将收到 -1。这是因为您使用 %dfloat 打印为 int。大多数平台中的float为4字节(使用sizeof(float)检查)。float 数字 2000 的二进制值为 01000100111110100000000000000000 并且它标记为 float 因此当您尝试使用 %d 打印它,它遇到了未定义的行为。

关于c - 为什么浮点指针的取消引用设置为 int 变量的地址打印为 `0` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com