I need some help - next piece of code writes a long double dynamic array into the file
int nx = 10, ny = 10;
long double **data = new long double *[nx];
long double **data_read = new long double *[nx];
for (int i = 0; i < nx; i++) {
data[i] = new long double [ny];
data_read[i] = new long double [ny];
}
data[4][4] = 10.0;
printf("%LF\n", data[4][4]);
FILE *file = fopen("data", "wb");
fwrite(data, nx * ny * sizeof(data), 1, file);
fclose(file);
file = fopen("data", "rb");
fread(data, nx * ny * sizeof(data_read), 1, file );
fclose(file);
printf("%LF\n", data_read[4][4]);
But data[4][4] != data_read[4][4]
, because after reading from file data_read[4][4]=0.0
.
Anybody knows what am I doing wrong?
You need to write each row in your pointer array individually. A mass write will not work for pointer-to-pointer implementations of a fake 2D array (or nD).
For writing:
For reading:
Frankly, you're (un)fortunate the process didn't crash outright, as you were writing a bunch of memory addresses to your disk file (which a hex dump would have showed you), and were likely walking off the end of your pointer-array allocation during both operations.
That said, I'd start learning about the standard C++ IO library rather than using C-code in a C++ world (or fix the tag on this question).
Single Block Write/Read
You asked if it is possible to do this as a single block read/write. The answer is yes, but you must allocate the memory contiguously. If you still want a pointer-to-pointer array you can certainly use one. Though I recommend using
std::vector<long double>
for the data buffer, the following will demonstrate what I refer to:Output
Using a
std::vector<>
for an RAII SolutionAll those allocations can get messy, and frankly prone to problems. Consider how this is different:
Change your code to (see comments for details):
Edit:
If you want to format the data in a continuous memory, use
vector<long double>
orlong double data[nx*ny]
instead. Then you can easily write or read by: