Copy to matrix line binary file

I want to write each row of the matrix to a binary file. I'm trying to write 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 is appreciated,

Ted.

+3
source share
2 answers

In case the interjay rules were not sufficient:

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() );

The question is out of context: why a pointer ofile? (of course, not necessarily in this example)

0
source

Some problems:

  • &matrix[i]will give you a pointer to an object vector<uint32_t>. If you want the pointer to this vector to contain data, use &matrix[i][0].

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

  • sizeof(uint32_t * x) sizeof(uint32_t) * x.

  • for for. .

+5

Source: https://habr.com/ru/post/1784852/


All Articles