Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want the comfort of named fields (<code>bar1</code> .. <code>barN</code>) and something like an array you can loop over to automate the operations. First we define the struct (a dense representation of the fields in memory):</p> <pre><code>struct VectorFields { int a; int b; int c; }; </code></pre> <p>Then we need to get to know the number of the fields used in that struct:</p> <pre><code>#define VECTOR_FIELDS_LEN (sizeof(struct VectorFields) / sizeof(int)) </code></pre> <p>(In C++ you could use some template magic foo, here we just use the preprocessor as a simpler variant). Next, we combine the <code>struct VectorFields</code> with an array of <code>int</code> so both match in size, also known as <code>union</code>:</p> <pre><code>union Vector { struct VectorFields fields; int raw[VECTOR_FIELD_LEN]; }; </code></pre> <p>(Note: <code>VECTOR_FIELD_LEN</code> must be a known constant value to the compiler, hence the preprocessor thingy before.) You are now able to access the data either by it's name (<code>.fields.a</code>) or by an index (<code>.raw[0]</code>). So, let's write the function which adds the <code>Vector</code> together:</p> <pre><code>void vector_add(union Vector* result, union Vector* a, union Vector* b) { int i; for (i = 0; i &lt; TUPLE_LEN; i++) { result-&gt;raw[i] = a-&gt;raw[i] + b-&gt;raw[i]; } } </code></pre> <p>You might use it like this then:</p> <pre><code>#include &lt;stdio.h&gt; int main() { union Vector a = { .fields = { 1, 2, 3 } }; union Vector b = { .fields = { 4, 5, 6 } }; union Vector sum; vector_add(&amp;sum, &amp;a, &amp;b); printf("%d %d %d\n", sum.fields.a, sum.fields.b, sum.fields.c); return 0; } </code></pre>
    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.
    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