c++ - 循环 - 访问冲突写入位置 0xabababab

标签 c++ loops

当我将循环设置为迭代 10 次时,它会工作,但是无论我设置多少次迭代,它总是在第 12 次时出现此错误。这是下面的代码。

有人知道为什么会这样吗?或者如果我遗漏的代码中存在逻辑错误。谢谢

string* Analyser::topFiveBuyers()
{
//set size and add buyer names for comparison.
string *calcString = new string[sSize];
int calcTotal[sSize] = {INT_MIN, INT_MIN, INT_MIN, INT_MIN, INT_MIN};

//checks transactions
for (int i = 0; i<nTransactions; i++)
{
    //compares with arrays
    for(int j =0; j<sSize; j++)
    {

    if(calcTotal[j] < calcTotal[j+1])
    {
    int tVar = calcTotal[j+1];
    string tStr = calcString[j+1];
    int tVarTwo = calcTotal[j];
    string tStrTwo = calcString[j];

    calcTotal[j] = tVar;
    calcString[j] = tStr;
    calcTotal[j+1] = tVarTwo;
    calcString[j+1] = tStrTwo;
    }

        if(tArray[i].buyerName == calcString[j])
        {
        calcTotal[j] += tArray[i].numShares;
        break;
        }
        else
            {
                //checks if shares is great then current total then replaces
                if(tArray[i].numShares > calcTotal[j])
                {
                    int tVar = calcTotal[j];
                    calcTotal[j+1] = tVar;
                    string tStr = calcString[j];
                    calcString[j+1] = tStr;
                    calcTotal[j] = tArray[i].numShares;
                    calcString[j] = tArray[i].buyerName;
                    break;
                }
            }
    }
}
return calcString;

最佳答案

您正在访问 calcString[j+1]calcTotal[j+1] 并且 j 等于 sSize- 1 在最后一次循环运行时。所以你要超出数组边界。

关于c++ - 循环 - 访问冲突写入位置 0xabababab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15386480/

相关文章:

c - 当 while 循环中的条件涉及一个在循环内获取值的变量时,我应该使用哪个循环?

actionscript-3 - Flash CS6 AS3,重置声音 channel

javascript:无法让 setTimeout 正常工作

c++ - 如何在最后一个节点中使奇数偶数LinkedList因子?

c++ - Codelite C++ 程序未编译和运行

c++ - 调用 QObject 的函数移动到 Qt 中的不同线程?

JavaScript:循环遍历字符串,如果字符串第一个字母包含元音,则返回字符串 + 'ay'

c++ - 错误 C2064 : term does not evaluate to a function taking 1 arguments, 如何克服此错误?

c++ - 封装与数据隐藏

javascript - 减少 JavaScript 中的对象数组