Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating Pascal's Triangle (Unstable Code)
    primarykey
    data
    text
    <p>There are two questions concerning the code posted below:<br/><br/> &nbsp;&nbsp;&nbsp;&nbsp;1) When I run this code on CodeBlocks, the code sometimes successfully runs (returning 0) but usually results in an error after it shows all the results (returning -1073741819). Why is this the case?<br/><br/> &nbsp;&nbsp;&nbsp;&nbsp;2) The values are all correct except for the last element of the array where the value should be 1 (pTriangle[20] = 1). However, I am getting some garbage number at the end, what am I doing wrong? <br/><br/> I have realized I could arrive at the same result with binomial coefficients but I still have no idea why I am getting the error and it'd be best if my mistake can be found. <br/><br/> <strong>Update1</strong>: <br/> <code>pTriangle[i] = temp[i % 2 ? 0 : 1] + pTriangle[i];</code> seems to be the problem. When I have commented this code, the program did not crash. I am trying to find out why it is crashing and trying to find a solution around it :)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define LEVEL 20 int main() { int *pTriangle = (int*)malloc(sizeof(int)*(LEVEL+1)); int i; for (i = 0; i &lt; LEVEL; i++) pTriangle[i] = 0; createPascalTriangle(pTriangle, LEVEL); for(i = 0; i &lt; LEVEL+1; i++) printf("pTriangle[%d]: %d\n", i, pTriangle[i]); free(pTriangle); return 0; } int createPascalTriangle(int *pTriangle, int level){ if (level &lt;= 0) return 0; pTriangle[0] = 1; pTriangle[1] = 1; int i; for ( i = 2; i &lt;= level; i++) increasePascalTriangleOneLevel(pTriangle); return 1; } int increasePascalTriangleOneLevel(int *pTriangle){ int i = 1; int temp[2] = {0}; temp[0] = pTriangle[0]; while (pTriangle[i] != 0){ temp[i % 2] = pTriangle[i]; pTriangle[i] = temp[i % 2 ? 0 : 1] + pTriangle[i]; i++; } pTriangle[i] = 1; return 1; } </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.
 

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