Writing Two Dimensional Array to Binary File

I am trying to write a two dimensional array to a binary file and I can't figure out the correct syntax. So far I have:

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
int n, i;
fstream myFile;

cout<<"Enter the dimension of the array"<<endl;
cin>>n;

int count[n][n];

for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
count[n][n] = 0;
}
}

//Then I have some lines that assign a count to each position in the array but it is not exactly relevant here.

myFile.open("image.bin", ios::out|ios::binary);
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
myFile.write((&count[i][j]),n*n);
}
}
myFile.close();
return 0;
}
Either
1
2
3
for( int i = 0; i < n; i++ )
   for( int j = 0; j < n; j++ )
      myFile.write( (char*)&count[i][j], sizeof(int) );
to write each integer separately, or
myFile.write( (char*)&cout[0][0], n*n*sizeof(int) );
to write them all together.
The result will be the same if the array is static. Though you might want to write n first, so that you know how much to read when you need to.
Topic archived. No new replies allowed.