我找不到导致我的数组在运行两次案例并退出后损坏的错误

I can not find the error that causes my array to get corrupted after running the case twice and exiting

本文关键字:案例 两次 退出 错误 损坏 找不到 我的 数组 运行      更新时间:2023-10-16

大家好,我得到了一个Run-Time Check Failure #2 - Stack around the variable 'barray2' was corrupted. 当我循环两次或更多相同的情况时,以及当我决定用 e 表示退出来打破 while 循环时,就会发生这种情况。 这是我的代码示例。 完成后我必须清除数组吗? 我尝试添加一个 barray[16]={0}; 打印后在机箱内,但我得到一个表达式错误, 我不知道:(

#include<iostream>
#include<iomanip>
#include<array>
using namespace std;
int main()
{
    int num(0),k(0);
    int barray[16]={0};
    int num2(0),k2(0);
    int barray2[16]={0};
    int choice(2);
    int choice2;
    char option;

    while(choice != -1) 
    {

    cout << "enter a choice from B, O, or e(exit)" <<endl;
    cin >> option;
    if (option == 'B' || option == 'b')
    choice2 = 1;
    else if (option == 'O' || option == 'o')
    choice2 = 2;
    else if (option == 'e')
    choice2 = -1;
    else
    choice2 = 0;

    switch(choice2)
    {
    case 1:
    cout<<"please enter integer number to be converted to binary (lessthan 65536) "<<endl;
    cin>>num;
    while ((num !=0) && (k<=15))
    {
        barray[k]=num%2;
        num=num/2;
        k++;
    }
    for (k=15;k>=0;k--)
    {
        cout<<barray[k];
        if ((k%4)==0)
        cout<<" ";
    }
    cout<<endl;
    break;
    case 2:
    cout<<"please enter integer number to be converted to octal (lessthan 65536) "<<endl;
    cin>>num2;
    while ((num2 !=0) && (k2<=15))
    {
        barray2[k2]= num2 % 8;
        num2 = num2 / 8;
        k2++;
    }
    for (k2=15; k2>=0; k2--)
    {
        cout<<barray2[k2];
        if ((k2%4)==0)
        cout<<" ";
    }
    cout<<endl;
    break;
    case -1:
    cout << "you entered " << choice2 << endl;
    choice = -1;
    break;
    default:
    cout << "try again " << endl;

    }

    }

}

您不会重新初始化计数器kk2

下面引用的循环在完成后保留kk2设置为 -1。 因此,在 while 循环的第二次传递中,您写入数组之前的一个索引:

for (k=15;k>=0;k--)
{
}
for (k2=15; k2>=0; k2--)
{
    //...
}

为了清楚起见,我将在每个使用它的while循环之前显式初始化k/k2

k = 0;
while ((num !=0) && (k<=15))
{ 
    //...
}

(同样适用于另一个带有 k2 的循环。