Convert an array of doubles to float

Hello everyone

I have a fairly big array of doubles that I wish to convert to float. The problem is that I can't allocate a new float array (there isn't enough memory). So I thought: why can't I use the double array to store the information, since I won't need the double information after I read it?
The idea is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

#define SIZE 1000

using namespace std;

int main () {
	
	float* f;
	double* d;
	d = new double[SIZE];
	
	// filling double array with some numbers
	for (int i=0; i<SIZE; ++i) d[i] = i*0.5;

	
	// assign float pointer to the same address as the double pointer... Ouch
	f = (float*)d;

	
	// write some pointer addresses
	cout << d << " " << &d << " " << &d[0] << " " << &d[1] << endl;
	cout << f << " " << &f << " " << &f[0] << " " << &f[1] << endl;

	
	// write what's written in the memory addresses corresponding to both pointers
	cout << "\nbefore" << endl;	
	cout <<  d[0] << " " << d[1] <<  " " << d[SIZE-1] << endl;
	cout <<  f[0] << " " << f[1] <<  " " << f[SIZE-1] << endl;

	
	// converting floats on double space
	for (int i=0; i<SIZE; ++i) f[i] = (float)d[i];

	
	// what's on the memory addresses after the cheating
	cout << "\nafter the cheating" << endl;
	cout << d[0] << " " << d[1] << " " << d[SIZE-1] << endl;
	cout << f[0] << " " << f[1] << " " << f[SIZE-1] << endl;
	
	
	// deallocate
	delete[] d;
	
	
	// what's on the memory addresses after deallocating double
	cout << "\nafter the deallocatin" << endl;
	cout << d[0] << " " << d[1] << " " << d[SIZE-1] << endl;
	cout << f[0] << " " << f[1] << " " << f[SIZE-1] << endl;
	
		
	return 0;

}



giving me perfect results!

of course nothing guarantees me that the next time I allocate some memory I won't get my floats erased.

I am aware this is memory corruption, lousy programming, you name it...

What would be the best practice?
I can't believe that to down-convert an array extra memory has be allocated..

Or... is it possible to use fwrite to save a double array as float? (I know that saving the first 4 bytes of an 8 byte variable won't truncate the extra precision).

Anything will do, as long as I don't have to use more memory!

EDIT: do I have a guarantee that the double array is contiguously allocated in memory? I mean, all addresses from d[0] to d[N] separated by 8 bytes?

Thank you for reading,
Best regards
Last edited on
That's fine, but not optimal.

The problem is that you are abusing the type system...


An array is always contiguous memory.

You could consider using a std::deque if you want to better utilize memory, and use the std::copy() algorithm to move values from the double to the float.

Good luck!
Topic archived. No new replies allowed.