阵列周围的堆栈已损坏C++

C++ stack surrounding array is corrupted

本文关键字:已损坏 C++ 堆栈 周围 阵列      更新时间:2023-10-16

我试图阅读一些关于变量周围的堆栈已损坏的不同帖子,但在将答案连接到我的代码时遇到问题。我想知道为什么我总是收到一条错误消息,说 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)*/ } 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); 

因为当索引已经超过分配的scoreArray空间时,您的do...while循环会进入另一个迭代。