0

Let's suppose head1 is an 2D array of float and I want to fill it with values read from the binary file file. After opening the file with

ifstream file ("myfile.bin", ios::in|ios::binary);

I tried two different ways:

  1. file.read( reinterpret_cast<char*>(&head1), sizeof(head1) );
  2. file.read( (char*) &head1, sizeof(head1) );

Both solutions work, but what's exactly the difference between them? which is "safer"? After reading some documentation, for me the role of reinterpret_cast is still a bit obscure and from "Programming: Principles and Practice Using C++" I also read that is better to use this function only if necessary especially for portability problem. Thanks

holdtheline
  • 103
  • 3
  • check my question about binary files https://stackoverflow.com/questions/70405642/how-to-store-class-object-having-string-in-binary-file – zain ul din Mar 16 '22 at 10:37
  • 2
    This is an occasion when using `reinterpret_cast` is acceptable, IMHO. And that is *always* better than using a "c-style" cast. Note also, that if `head1` is a plain array, you don't need the `&` before it, as it will "decay" to a pointer to its first element in most expressions. – Adrian Mole Mar 16 '22 at 10:40
  • attention: sizeof() only works for static arrays, not for ```float* head1 = new float[1024];```. Here, sizeof() returns the size of a pointer variable (4 or 8 bytes e.g.). – KungPhoo Mar 16 '22 at 10:47

0 Answers0