Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>By using the &amp; operator, you're getting a pointer to the contents of the variable (think of it as just a memory address).</p> <pre><code>float a = 123.45f; float* p = &amp;a; // now p points to a, i.e. has the memory address to a's contents. char* c = (char*)&amp;a; // c points to the same memory location, but the code says to treat the contents as char instead of float. </code></pre> <p>When you gave the (char*)&amp;randomValue for write(), you simply told "take this memory address having char data and write sizeof(randomValue) chars from there". You're not writing the address value itself, but the contents from that location of memory ("raw binary data").</p> <pre><code>cout &lt;&lt; reinterpret_cast&lt;char*&gt;(&amp;intArray[i]); //the char* value of each one </code></pre> <p>Here you're expected to give char* type data, terminated with a null char (zero). However, you're providing the raw bytes of the float value instead. Your program might crash here, as cout will input chars until it finds the terminator char -- which it might not find anytime soon.</p> <pre><code>float randomValue = 23.14f; char* charValue = reinterpret_cast&lt;char*&gt;(&amp;randomValue); float back = *(float*)charValue; </code></pre> <p>Edit: to save binary data, you simply need to provide the data and write() it. Do not use &lt;&lt; operator overloads with ofstream/cout. For example:</p> <pre><code> int values[3] = { 5, 6, 7 }; struct AnyData { float a; int b; } data; cout.write((char*)&amp;values, sizeof(int) * 3); // the other two values follow the first one, you can write them all at once. cout.write((char*)&amp;data, sizeof(data)); // you can also save structs that do not have pointers. </code></pre> <p>In case you're going to write structs, have a look at <em>#pragma pack</em> compiler directive. Compilers will align (use padding) variable to certain size (int), which means that the following struct actually might require 8 bytes:</p> <pre><code>#pragma pack (push, 1) struct CouldBeLongerThanYouThink { char a; char b; }; #pragma pack (pop) </code></pre> <p>Also, do not write pointer values itself (if there are pointer members in a struct), because the memory addresses will not point to any meaningful data once read back from a file. Always write the data itself, not pointer values.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload