reinterpret_cast problem

Started by
14 comments, last by jnmacd 11 years, 1 month ago

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?

Advertisement

The pointer ma points to the beginning of the aha array. The memset function then writes "something" to the first double of ma, which is the first double of the aha array. That is why the first element of aha is borked, and the remaining four elements are not

Well you are pointing to the first element in the array, then modifying only sizeof(double) bytes.
Any memory after sizeof(double) bytes should be unaffected.

To modify all,
memset(ma,1,sizeof(double)*5);
This has nothing to do with reinterpret_cast.

Still,the exercise asks: Why was not each element set to 1? I have no ideea how to explain it

Do you know what the memset() call does?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

changes the value of the bytes

http://en.wikipedia.org/wiki/Binary64


Read the "Double Precision Examples" section. Now, what you're doing is you're filling the bytes with: 01 01 01 01 01 01 01 01


The bytes are not being CASTED back to doubles. You are directly modifying the 8 bytes INSIDE each double.

Well you are pointing to the first element in the array, then modifying only sizeof(double) bytes.
Any memory after sizeof(double) bytes should be unaffected.

To modify all,


memset(ma,1,sizeof(double)*5);
This has nothing to do with reinterpret_cast.

Wouldn't that just bork all of the array instead of just the first double?

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Still,the exercise asks: Why was not each element set to 1? I have no ideea how to explain it

Because you aren't setting each double to 1.0 -- you are setting each individual byte for the first double to 0x01. The layout for your double will be 0x0101010101010101, which is around 7.784e-304, according to IEEE-754.

You probably want to use std::fill instead:
double arr[4] = {};std::fill( arr, arr+4, 1. );

(Also, 1.0 looks like 0x3FF0000000000000 in memory.)

It says this:

after using reinterpret cast .... set each byte of the array to 1

This topic is closed to new replies.

Advertisement