C ++堆栈周围的数组已损坏

时间:2014-09-06 12:17:39

标签: c++ stack corrupt

我试过阅读一些关于围绕变量的堆栈已损坏的不同帖子,但是在将答案连接到我的代码时遇到了问题。我想知道为什么我一直收到一条错误消息,指出围绕 scoreArray 的堆栈已损坏。我尝试使用多个变量来增加数组上的位置。我知道代码写得不好,但如果有人能帮助我理解为什么我会收到这条消息,我将不胜感激。

非常感谢你。

double sum = 0.0; 

double SumFunction(double printArray[]);

int i = 0;
int j = 0; 

const int SIZE = 4;

void main()
{
    double input = 0.0;
    vector<double> scores;
    double scoreArray[SIZE];

    do
    {
        cout << "Please enter a decimal value: ";
        cin >> input;

        scores.push_back(input);
    } while (scores.size() <= SIZE);

    do
    {
        int z = 0; 
        scoreArray[i] = scores[z];
        i++;
        z++;
    } while (i <= SIZE); 
    SumFunction(scoreArray);

    cout << sum; 

    system("PAUSE"); 
}

double SumFunction(double printArray[])
{
    do
    {
        sum += printArray[j]; 
        j++; 
    } while (j <= SIZE); 

    return sum; 
}

1 个答案:

答案 0 :(得分:4)

由于:

/*(1)*/ } while (scores.size() <= SIZE);
/*(2)*/ } while (i <= SIZE); 
/*(3)*/ } while (j <= SIZE); 

应该是:

/*(1)*/ } while (scores.size() < SIZE);
/*(2)*/ } while (i < SIZE); 
/*(3)*/ } while (j < SIZE); 

因为当{1}}循环已超过do...while的分配空间时,您的scoreArray循环会进入另一次迭代。

相关问题