我找不到导致我的数组在运行两次案例并退出后损坏的错误
I can not find the error that causes my array to get corrupted after running the case twice and exiting
大家好,我得到了一个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;
}
}
}
您不会重新初始化计数器k
和k2
。
下面引用的循环在完成后保留k
和k2
设置为 -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
的循环。
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 对结构向量进行两次排序
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- 我找不到导致我的数组在运行两次案例并退出后损坏的错误