Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

whole big array from heap to file without for loop in C++

A big array on the heap, initialized like this:

 double* vx = new double[1024/8 * 1024 * 1024];

wants to be directly saved to a file like this:

file.write((char*)&vx, sizeof(1024 / 8 * 1024 * 1024));

This only writes the first value but the idea should be clear.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

vx is already a pointer. By taking its address again (&vx) you tell write to write the memory contents at the memory location where that pointer is stored rather than where the pointer points to.

Moreover, your second parameter is wrong. sizeof( ...some integers ...) is the same as sizeof(int). It should be the number of bytes to be written. That is number of elements * sizeof(double). Note that sizeof has no buisness in determining the number of elements in an array. You cannot retrieve the number of elements from the pointer vx and to query the number of elements from an array you would use std::size.


So many problems are caused by confusing arrays with pointers. vx is not an array. It points to the first element of an array. write needs the memory location of the array, which coincides with the memory location of its first element.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading