I'm reading a book,and I have an exercise that gives me problems.Here's the code:
double aha [5] = {0,0,0,0,0};
unsigned char* ma = reinterpret_cast<unsigned char*>(&aha[0]);
memset(ma,1,sizeof(double));
function_to_cout_all_elements_of_aha(aha);
The problem is,it prints this:
7.784e-304
0
0
0
0
What's happening to the first element?! Why the other 4 are fine,and the first one got screwed up?
If you want to write to all 5 elements, you would have to change your memset function:
memset(ma,1,sizeof(double) * 5);
Note the "*5" multiplication (that's because there are 5 doubles)
Size of double is usually 8 bytes, so 8 bytes * 5 elements = memset 40 bytes
As for the question in the book, it's trying to make you realize what's going on.
The first double in memory is filled like this: "0x0101010101010101", but it doesn't mean that the double will contain "01", not even "101010101010101" or something like that.
If you play with an online binary to floating point conversor and see how the value "0x01010101" converts to "2.3694278E-38". Note that the conversor works with 32-bit floats, not with 64-bit doubles.
The only exception is when doing memset( ma, 0, sizeof(double) * 5 ); because that sets the double(s) to 0x0000000000000000; and IEEE 754-compatible floats & doubles have the property that this value corresponds to "0.0", which makes memset a great way to zero your array. But you can't use it to set it to any other values, because then it won't match.
Hope this explanation helps