递增数组中的元素时进程意外终止

Process terminated unexpected when increment elements in array

这段代码有什么问题?

导致错误的那个:

 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];
        }
}

错误是:进程在 Code::Blocks

中终止,状态为 -1073741819(0 分钟,3 秒)

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(索引),递增计数,然后检查边界。有效的循环增加了索引的变化(cnt)。

tempsum 的添加使其超出了 sumCount 的范围。当您尝试在该状态下增加计数时,进程因无效内存访问而终止。