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
.
(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.)