Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Conceptually, this is OK - but you have to do some additional work to ensure it will work reliably.</p> <p>A potential problem is that you cannot just access any arbitrary address as a <code>float</code>. There may be specific <em>alignment</em> requirements - the address returned by <code>malloc()</code> is required to be correctly aligned for access as any type, but once you add 14 to that address, all bets are off (except for <code>char</code>).</p> <p>To ensure the correct alignment, you must ensure that the address you add to <code>buffer</code> is a multiple of <code>sizeof(float)</code>. You can do that by adding padding using the following formula:</p> <pre><code>#define PAD_OFFSET(offset, type) ((offset) + sizeof(type) - 1) &amp; ~(sizeof(type) - 1)) float *float_buffer = (float *)(buffer + PAD_OFFSET(14, float)); </code></pre> <p>Note that this will create a gap - <em>padding</em> - between your chars and your floats.</p> <p>Alternatively, you can define a <code>struct</code>, and the compiler will figure the padding out for you. This uses a C99 feature called a <em>flexible array member</em>:</p> <pre><code>struct foo { char abc[14]; float xyz[]; }; struct foo *buffer = malloc(2062); memcpy(&amp;buffer-&gt;abc, header, 14); some_function(&amp;buffer-&gt;xyz); transmit(buffer); /* Presuming transmit() expects a void * parameter. */ </code></pre> <p>If you wish to do it <em>without</em> padding, you cannot directly access the memory in <code>buffer</code> as floats - you will have to create a temporary array and copy it in:</p> <pre><code>float temp[500]; /* Or whatever size */ some_function(&amp;temp); memcpy(buffer + 14, temp, sizeof temp); </code></pre>
    singulars
    1. This table or related slice is empty.
    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. 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.
    3. 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