简体   繁体   English

Memcpy与C ++中的浮点数

[英]Memcpy with floats in C++

I am having a problem with what would appear to be extremely simple code, yet it dosent do at all what I'd expect it to: 我对看起来非常简单的代码有疑问,但是它根本无法达到我的期望:

Code: 码:

char b[sizeof(float)];
float a = 1.5f;
memcpy(b, &a, sizeof(float));
printf("%f\n", b[0]);

Output: 输出:

62827075002794546937726511559700164562271693617156259118887055013962964939146547
22493354730179062365918845182857228200743453702107162763566167344423902681816648
14169764096333089859051972349071751428406066879715295195780847944297207011246001
33742258486014791122944.000000

Yet it works when I do this: 但是当我这样做时它起作用:

char b[sizeof(int)];
int a = 3;
memcpy(b, &a, sizeof(int));
printf("%i\n", b[0]);

Output: 输出:

3

Why does this happen? 为什么会这样? Is it because of endianness or something? 是因为字节顺序还是其他原因?

Your code has undefined behaviour. 您的代码具有未定义的行为。 The expression b[0] is a char (promoted to int ), and the format specifier %f expects a double . 表达式b[0]是一个char (提升为int ),格式说明符%f期望double

(There could be any number of explanations for the output you see. The most urgent one that comes to mind is that a double is wider than an int on your platform and garbage memory is read. If you want a slightly more predictable experiment, try passing static_cast<uint64_t>(b[0]) as the argument.) (对于您看到的输出,可能有很多解释。想到的最紧急的解释是,平台上的double宽度比int宽度大,并且读取了垃圾内存。如果您想进行更可预测的实验,请尝试传递static_cast<uint64_t>(b[0])作为参数。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM