There are two questions regarding the code below:
1) When I run this code in CodeBlocks, the code sometimes successfully runs (returns 0), but usually results in an error after it shows all the results (return -1073741819). Why is this so?
2) All values ββare correct, except for the last element of the array, where the value must be 1 (pTriangle [20] = 1). However, I get some trash at the end, what am I doing wrong?
I realized that I can get the same result with binomial coefficients, but I still don't know why I get the error, and it would be better if my error were found.
Update1 :
pTriangle[i] = temp[i % 2 ? 0 : 1] + pTriangle[i]; seems like a problem. When I commented on this code, the program did not work. I am trying to find out why it is crashing and trying to find a solution around it :)
#include <stdio.h> #include <stdlib.h> #define LEVEL 20 int main() { int *pTriangle = (int*)malloc(sizeof(int)*(LEVEL+1)); int i; for (i = 0; i < LEVEL; i++) pTriangle[i] = 0; createPascalTriangle(pTriangle, LEVEL); for(i = 0; i < LEVEL+1; i++) printf("pTriangle[%d]: %d\n", i, pTriangle[i]); free(pTriangle); return 0; } int createPascalTriangle(int *pTriangle, int level){ if (level <= 0) return 0; pTriangle[0] = 1; pTriangle[1] = 1; int i; for ( i = 2; i <= 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; }
kpark source share