I've created a program that saves an array into a file and then reads the file to show the array on the screen. This is the code
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int saveSize = 5;//size of the array
int save [saveSize + 1] = {saveSize, 7, 1, 2 ,3, 4}; //creating an array which first element is his own size
ofstream fileWrite; fileWrite.open ("File.dat", ios::out | ios::binary | ios::trunc);
fileWrite.write((char *) &save, sizeof(save)); //saves the array into the file
fileWrite.close();
int sizeLoad; //size of the array that will be loaded
ifstream fileRead; fileRead.open("File.dat", ios::in | ios::binary);
fileRead.read((char *) &sizeLoad, sizeof(int)); //it only reads the first element to know the size of the array
int load[sizeLoad+1]; //creating the array
fileRead.read((char *) &load, sizeof(int));
fileRead.close();
//showing the array
for(int i = 1; i <= sizeLoad; i++) cout << "Element " << i << ": " << load[i] << endl;
return 0;
}
The problem is that when I run the program, that´s the result:
Element 1: 2686224
Element 2: 1878005308
Element 3: 32
Element 4: 2686232
Element 5: 4199985
Not even close. Somebody knows why it shows that?