Arun
Arun

Reputation: 3408

C++ double ptr to long ptr conversion

Consider the below code fragment:

double * p = new double[16];

int value = 1;
void * q = p;
*((double *)q) = value;

int x = ((long *)p)[0];

cout << "Value of x for double * to long * = " << x << endl;

*((int *)q) = value  ;

x = ((long *)p)[0];

cout << "Value of x for int * to long * = " << x << endl;

Here the outputs are 0 and 1 respectively. Can anyone explain to me why?

Also if I directly access the value at pointer...ie. p[0], the value is correctly shown as 1 in both case. Why?

Upvotes: 0

Views: 1045

Answers (1)

DrYap
DrYap

Reputation: 6647

Integers are stored in memory in straight binary so you can convert between intand long with no problem. doulbe is stored using the floating point binary syntax where some of the bits are used to describe the mantissa and the others are used to describe the exponent (similar to scientific notation i.e. 5e2 = 500).

If you try and use the data for a double as the data for a double then it will not convert correctly due to the different ways that the binary stores the value.

Upvotes: 1

Related Questions