Roman
Roman

Reputation: 117

C++ Save and load float, addressed by a pointer, to a binary file

I'm trying to make a "Save / Load" sequence to a dynamic array of floats (float*). I have an array that holds the data as a float4 *dst;.

I have this piece of code for saving the array

int sz = properties.height * properties.width;
float * d_array = (float*)malloc(4 * sizeof(float) * sz);

for (size_t i = 0; i < sz; i++, dst++)
{
    d_array[4 * i + 0] = dst->x;
    d_array[4 * i + 1] = dst->y;
    d_array[4 * i + 2] = dst->z;
    d_array[4 * i + 3] = dst->w;
}

// Up to this point, everything works great
ofstream outS(backupdata, ios::out | ios::binary);
outS.write((char *)&d_array, 4 * sz * sizeof(float)); // <- This is where the code breaks
outS.close();

This is the error that I'm getting:

Unhandled exception at 0x00007FFDC83316EE (vcruntime140d.dll) in myproject.exe: 0xC0000005: Access violation reading location 0x000000FECA900000.

but when I remove the sz from the pointer error line, it works fine (though obviously it doesn't get to the entire array)

What's am i missing? is the write function limited by memory? and if so, how can I overcome this issue?

Upvotes: 0

Views: 1167

Answers (1)

bruno
bruno

Reputation: 32594

just do

outS.write((char *)d_array, 4 * sz * sizeof(float)); 

d_array values the address of the array whose content has to be saved

using &d_array you (try to) save the address of d_array then the memory after it

Upvotes: 4

Related Questions