在数组中增加元素时进程意外终止



这段代码有什么问题?

导致错误的那个:

 for(int i=0; primeArr[i]!=0; ++i)
{
    int tempSum=0;
    for(int j=i; primeArr[j]!=0 && tempSum<=10000; ++j)
    {
        tempSum=tempSum+primeArr[j];   //error happend here, if this code is discared it will no longer terminated
        sumCount[tempSum]++;           //same as above, if discarded the code will be okay
    }
}

没有错误的:

     for(int i=0; primeArr[i]!=0; ++i)
{
        int flag=i, cnt=primeArr[flag];
        while(cnt<=10000)
        {
            sumCount[cnt]++;
            ++flag;
            cnt+=primeArr[flag];
        }
}

错误为:Process terminated with status -1073741819 (0 minute(s), 3 second(s)) in Code::Blocks

j可能超出了primeArr数组的范围。即j等于或大于primeArr数组中的元素个数。

要解决这个问题,首先将primeArr数组中的元素数量存储到变量arrLength中。然后,在循环中添加另一个检查条件:

for(int i=0; i < arrLength && primeArr[i]!=0; ++i)
{
    int tempSum=0;
    for(int j=i; j < arrLength && primeArr[j]!=0 && tempSum<=10000; ++j)
    {
        tempSum=tempSum+primeArr[j];   //error happend here, if this code is discared it will no longer terminated
        sumCount[tempSum]++;           //same as above, if discarded the code will be okay
    }
}

第二段代码相同:

for(int i=0; i < arrLength && primeArr[i]!=0; ++i)
{
        int flag=i, cnt=primeArr[flag];
        while(cnt<=10000)
        {
            sumCount[cnt]++;
            ++flag;
            cnt+=primeArr[flag];
        }
}

添加到tempsum(索引),增加计数,然后检查边界。有效的循环对索引的变化进行加1 (cnt)。

加上tempsum使其超过sumCount的边界。当您尝试在该状态下增加计数时,进程将因无效的内存访问而终止。

最新更新