[英]Creating Pascal's Triangle (Unstable Code)
There are two questions concerning the code posted below: 关于下面发布的代码有两个问题:
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). 1)当我在CodeBlocks上运行此代码时,代码有时会成功运行(返回0),但通常会在显示所有结果后返回错误(返回-1073741819)。 Why is this the case?
为什么会这样?
2) The values are all correct except for the last element of the array where the value should be 1 (pTriangle[20] = 1). 2)除了数组的最后一个元素值(1)(pTriangle [20] = 1)之外,这些值都是正确的。 However, I am getting some garbage number at the end, what am I doing wrong?
但是,我最后得到一些垃圾号码,我做错了什么?
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. 我已经意识到我可以用二项式系数得到相同的结果,但我仍然不知道为什么我得到错误,如果我的错误可以找到它是最好的。
Update1 : Update1 :
pTriangle[i] = temp[i % 2 ? 0 : 1] + pTriangle[i];
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 :)
我试图找出它为什么崩溃并试图找到解决方案:)
#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;
}
The last element of the array hasn't been initialized. 数组的最后一个元素尚未初始化。
Write: 写:
for (i = 0; i < LEVEL + 1; i++)
pTriangle[i] = 0;
instead of: 代替:
for (i = 0; i < LEVEL; i++)
pTriangle[i] = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.