What does this code segment mean?

In the program in the link provided, what does the following code segment mean? I can't understand what it does and why we had to use a pointer here.

http://www.cppforschool.com/project/student-report-card-project.html

 
  outFile.write((char *) &st, sizeof(student));
The types.
1
2
3
4
student st;
ofstream outFile;
...
outFile.write( (char *) &st, sizeof(student) );

The outfile is an ofstream, so we should look at ofstream::write (actually it is ostream::write).
http://www.cplusplus.com/reference/ostream/ostream/write/
1
2
// Inserts the first n characters of the array pointed by s into the stream.
ostream& write( const char* s, streamsize n );

We have object 'st' that occupies sizeof(student) bytes. We pretend that there is a character array in that memory location. We write the bytes to a file.

The (char *) &st is a C-style cast syntax. C++-style syntax would be static_cast<char *>( &st )
Last edited on
Thank you so much
Topic archived. No new replies allowed.