C++ newbie here.
I'm trying to figure out the following line that writes a buffer into a file:
fOut.write((char *)&_data, sizeof(_data));
Contrary to your comment, the array must be automatic or static storage duration in order for
sizeof to work.
It should be just
(char*)_data. The name of an array implicitly converts to a pointer to the first element.
write expects a pointer, and stores the content found at that location, not the location's address.
_data is an array,
sizeof (_data) is the cumulative size of all elements in the array. If
_data were a pointer (such as when an array is dynamically allocated on the heap), you would want
numElems * sizeof(_data). Multiplying the size of a pointer by the number of elements isn't helpful.
It means that the content at that address will be treated as a series of individual bytes, losing whatever numeric meaning it might have had. This is often done to perform efficient bulk copy of data, either to and from a file, or with
memmove. The data type should be POD (plain old data) or you'll get unexpected results.
_data is a pointer to an array allocated from the heap, as your comment suggests, then the code is badly broken. In that case, you are saving just the address, and it may appear to work if you load the file back into the same instance of your program, but that's just because it's finding the data still in memory at the same address. The data wouldn't actually be in the file, and if you re-started the program before loading the file, you'd find that the data was gone. Make the changes I mentioned in both (1) and (3) in order to save the complete array regardless of whether it's allocated automatic, static, or dynamically.