Dereferenceing上铸造void指针浮动* / INT * [英] Dereferenceing on casting the void pointer to float*/int*

查看:135
本文介绍了Dereferenceing上铸造void指针浮动* / INT *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i = 10;
void *p = &i;
printf("%f\n", *(float*)p);

float i=10.00;
void *p = &i; // no change
printf("%d\n", *(int*)p);

为什么一个打印0.0,而不是10.0?如果我们改变A到B,那么它的输出就是垃圾。

Why does A print 0.0, not 10.0? If we change A to B, then its output is garbage.

推荐答案

要更precise对别人说什么,这里是一个考验:

To be more precise about what the others say, here is a test:

#include <stdlib.h>

int main()
{
    int a = 10;
    float b = 10;
    char * p;

    p = &a;
    printf("int repr: %02x %02x %02x %02x\n", p[0], p[1], p[2], p[3]);

    p = &b;
    printf("float repr: %02x %02x %02x %02x\n", p[0], p[1], p[2], p[3]);

    return 0;
}

的输出是

int repr: 0a 00 00 00
float repr: 00 00 20 41

这表明:

A)这是一个小端机,由于INT的最低字节至上内存
b)该int有重新presentation与字节 0A 00 00 00 ,因此该值 0000000A 的,好了,10六角重新presentation。
C)浮动的确 41200000 。据 IEEE 754 ,这意味着你有一个符号位,指数的8位和23位尾数。符号为0(+),指数为为0x82 ,意为+3,而尾数为 010000 ... ,这意味着在二进制1.01或1.25十进制。

a) It is a little endian machine, as the lowest byte of the int comes first in memory b) the int has the representation with the bytes 0a 00 00 00, so the value is 0000000a, the hex representation of, well, 10. c) the float is indeed 41200000. According to IEEE 754, this means you have one sign bit, 8 bits of exponent and 23 bits of mantissa. The sign is 0 (+), the exponent is 0x82, meaning +3, and the mantissa is 010000..., which means 1.01 in binary or 1.25 in decimal.

总之,这些数据构成了值2 * 2 * 2 * 1.25 = 8 * 1.25 = 10

Together, these data form the value 2*2*2*1.25 = 8*1.25 = 10.

这篇关于Dereferenceing上铸造void指针浮动* / INT *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆