浮点值转换为char [英] Float value casted to char

查看:102
本文介绍了浮点值转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,

#include<stdio.h>
int main(){
  char array[] = {'1', 2, 5.2};
  char* my_pointer = array[2];
  printf("%c", *my_pointer);
}

5.2 在内存中的IEEE 754表示形式中,由于小端格式, char 从此浮点表示形式中选择8位(第一位)。

5.2 is stored in IEEE 754 representation in memory, char picks 8 bits(first) from this float representation, due to little endian format.

C是一种松散类型的语言。允许将 float 转换为 char

C is a loosely typed language. Am allowed to cast float to char.

为什么该程序是核心转储?

Why the program is core dumped?

推荐答案

在程序中更改 char * my_pointer = array [2]; char * my_pointer =& array [2]; 作为指针应存储地址。

In your program change char *my_pointer = array[2]; to char *my_pointer = &array[2]; as pointer should store the address.

#include<stdio.h>
int main(){
  char array[] = {'1', 2, 45.2};
  char *my_pointer = &array[2];
  printf("%c", *my_pointer);
}

输出:

- //NOTE: asci value of - is 45


@AnT 中提到的

,当您转换 45.2 转换为 char 类型,编译器将生成加载 45.2 ,将值截断并将其存储为 45 并将其存储在您的 char 变量中,因此在打印时得到-作为输出。

as @AnT has mentioned in comments, when you convert 45.2 to char type, the compiler will generate code that loads 45.2, truncates the value and stores it in your char variable as 45, so when you print you get - as output.

这篇关于浮点值转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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