3

I want to write each row of a matrix to a binary file. I try writing it like this:

vector< vector<uint32_t> > matrix;

...

for(size_t i = 0; i < matrix.size(); ++i)
ofile->write( reinterpret_cast<char*>(&matrix[i]), sizeof(uint32_t*sizeof(matrix[i])) );
{
    for(size_t j = 0; j < numcols; ++j)
    {
        std::cout << left << setw(10) << matrix[i][j];
    }
    cout << endl;
}

but it doesn't work, I get garbage numbers.

Any help appreciated,

Ted.

Flethuseo
  • 5,969
  • 11
  • 47
  • 71

2 Answers2

5

Some issues:

  1. &matrix[i] will give you a pointer to a vector<uint32_t> object. If you want a pointer to that vector's contained data, use &matrix[i][0].

  2. sizeof(matrix[i]) is the size of the vector object itself, not its contents. Use matrix[i].size() to get the number of elements.

  3. Instead of sizeof(uint32_t * x), use sizeof(uint32_t) * x.

  4. The second for loop isn't actually nested in the first for loop. You need to rearrange your braces.

interjay
  • 107,303
  • 21
  • 270
  • 254
0

In case interjay's guidelines weren't enough:

vector< vector<uint32_t> > matrix;

for(size_t i = 0; i < matrix.size(); ++i) 
  ofile.write( (char*)&matrix[i][0], sizeof(matrix[i][0])*matrix[i].size() );

Out-of-context question: Why is ofile a pointer? (certainly don't need to be in this example)

sly
  • 1,722
  • 1
  • 10
  • 15