ostream write()

Hi, I am trying to figure out a piece of code, and one line is confusing me. I have put the code below. The line that I am confused with is the out.write. I believe the char pointer is meant to be the pointer to the buffer but what is the &n, is that still a part of the char* since there is no comma. Is it a char pointer to a reference of n?

1
2
3
4
5
6
7
8
9
10
11
12
13

  int n [5] = {1,2,3,4,5}
register int i;
  ofstream out ("test" , ios::out | ios::binary)
  if(!out)
{
cout <<"not open\n"
return 1;
}

out.write((char *) &n, sizeof n);

out.close();
I believe the char pointer is meant to be the pointer to the buffer
Yes.

but what is the &n
&n means the address of the n variable. It is getting a pointer to the buffer. It is different than reference semantics. Since n is an array in this case, &n means the address of the array, which is the pointer to the first element of the array. [Note: Arrays are kind of special, since it would implicitly decay into a pointer even without the & in this case, but in general you need it.]

When you do (char*)(some_buffer), this is called casting. It means "reinterpret the buffer currently being pointed to and use it as if it were pointing to an array of bytes (chars)". This just let's ofstream.write write the buffer to file as if it were a stream of bytes. [It's implementation-defined how exactly the data is laid out here, but in most normal systems you are going to have 4-byte, little-endian ints being written to file.]

So, in summary:
• n == your array object
• &n == the address of your array object
• (char*)&n == the address of your array object, reinterpreted as pointing to an array of chars.
Last edited on
Ok I think I understand now. Thank you.

I assume I don't need to cast it? (Guessing it's just this example) could I simply just give a pointer to the buffer, if I wanted to just output the data in the form it's in?
Why not try it yourself? It won't compile if you don't cast it.

ofstream.write writes bytes (i.e. chars). What do you mean by "form"? You already are outputting the data in the form that it's in; in the case of int, it's a 4-byte, little-endian segment of data on most systems (again, not every system).
Topic archived. No new replies allowed.