【探究实验】数据类型——指针类型转换——输出方式的探究

复制代码
#include<stdio.h>

int main(){
    //1
    int a=1;    
    printf("%d\n",(double)a);//猜想1
    printf("%d\n",*(double*)&a);//正常输出//猜想2+3
    printf("%d\n",(float)a);//猜想1
    printf("%d\n",*(float*)&a);//猜想2
    printf("\n");
    //2
    printf("%f\n",(double)a);//正常输出//猜想1
    printf("%f\n",*(double*)&a);//猜想1+2
    printf("%f\n",(float)a);//正常输出//猜想1
    printf("%f\n",*(float*)&a);//猜想2
    printf("\n");
    //3
    double b=1;
    printf("%f\n",(double)b);//正常输出//猜想1
    printf("%f\n",*(double*)&b);//正常输出//猜想1
    printf("%f\n",(float)b);//正常输出//猜想1
    printf("%f\n",*(float*)&b);//猜想2
    printf("\n");
    //4
    float c=1;
    printf("%f\n",(double)c);//正常输出//猜想1
    printf("%f\n",*(double*)&c);//猜想2
    printf("%f\n",(float)c);//正常输出//猜想1
    printf("%f\n",*(float*)&c);//正常输出//猜想1
    printf("\n");
    
    return 0;
}
复制代码

输出结果

复制代码
0
1
0
0

1.000000
0.000000
1.000000
0.000000

1.000000
1.000000
1.000000
0.000000

1.000000
0.000000
1.000000
1.000000
复制代码

问题1:指针类型的作用是什么?区域1中为什么转换为double类型指针的a可以输出,而转换为foalt类型指针的a不能输出?

问题2:int a;*(double*)&a写法的临时存储方式是什么?和变量的初始定义有关系吗?为什么%d输出可以而%f不能(%lf也不能)输出?为什么*(float*)&a写法的输出两种都不能?

 

猜想:

1。%d只能输出整型,%f只能输出浮点数

2。*(double*)&a 的写法 受且只受 强制转换 的限制:int* 和double*可以相互转换,但是float*不能和其他类型互换。

3。*(double*)&a如果成功得到的临时变量就是a。

 

猜想1在书上已经发现了,于是证明猜想2和3

//证明猜想---int
    int test=1;
    printf("%d\n",*(int*)&test);
    printf("%f\n",*(int*)&test);
    printf("%d\n",*(float*)&test); 
    printf("%f\n",*(float*)&test);
    printf("%d\n",*(double*)&test); 
    printf("%f\n",*(double*)&test);

结果:

1
0.000000
0
0.000000
1
0.007813
//证明猜想---double
    double test=1;
    printf("%d\n",*(int*)&test);
    printf("%f\n",*(int*)&test);
    printf("%d\n",*(float*)&test); 
    printf("%f\n",*(float*)&test);
    printf("%d\n",*(double*)&test); 
    printf("%f\n",*(double*)&test);

结果:

0
0.000000
0
0.000000
0
1.000000
//证明猜想---float
float test=1; printf("%d\n",*(int*)&test); printf("%f\n",*(int*)&test); printf("%d\n",*(float*)&test); printf("%f\n",*(float*)&test); printf("%d\n",*(double*)&test); printf("%f\n",*(double*)&test);

结果:

1065353216
0.000000
0
1.000000
1065353216
0.007813

实验结论:

猜想2和猜想3都是错误的。

除了int类型指针可以强制转换为double类型指针以外,int,double,float不能相互转换。

最终结论:

1整型和浮点数  输出类型必须与输出位的类型一致才能正常输出

2不同指针类型相互转换写法会产生未知的错误。写法建议只用于与void*相互转换的情况。

思考题:

1.整型和浮点数中,为什么只有int*可以转换为double*而且*得到的还是一个int类型?其中原理是什么?

2.test错误输出中的数字是怎么产生的?

思考任务:

理解指针类型与指针类型转换原理。

posted @   海底淤泥  阅读(433)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示