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.

>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.

Leave a Reply Cancel reply