Note that there are some explanatory texts on larger screens.

plurals
  1. POBuilding an array where each element depends on the previous
    primarykey
    data
    text
    <p>I'm building a set of arrays where each element depends on the previous element, and I'm having a hard time coming up with an elegant solution for setting the initial value. The code looks something like this:</p> <pre><code>int A[1024]; int B[1024]; /* ... more arrays... */ int i; for (i = 0; i &lt; 1024; i++) { /* do some work */ A[i] = A[i-1] + some_value(); B[i] = B[i-1] + some_other_value(); /* ... and so on... */ } </code></pre> <p>But of course this is an invalid memory access when <code>i</code> is 0. I know that the initial values of all arrays should be 0.</p> <p>There are several ways to solve this problem. I could put a giant <code>if</code> statement in the loop to check if <code>i</code> is 0. Seems clunky since it will only evaluate to <code>true</code> once. I could keep a temporary variable, initialized to 0, for each array, called <code>prev_val_of_A</code>, etc, that holds the value of the last iteration. I'd have to update it to the current value at the end of every iteration. This seems a little silly since, most of the time, the value I want is sitting right there in the array's previous element. I could fiddle with the meaning of the array, and adopt the convention that the <em>second</em> element in the array contains the value for the <em>first</em> iteration of the loop; that is, allocate for <code>A[1025]</code>, initialize <code>A[0]</code>, then in the loop, do</p> <pre><code>A[i+1] = A[i] + some_value(); </code></pre> <p>This seems confusing and might invite errors on further use of <code>A</code>.</p> <p>I'm looking for clean, elegant suggestions to solve this issue.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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