突然变量复位
Sudden variable reset
问题:
"maxPrint"突然重置为0。在函数"skaitymas"中,它遵循if,并将自身更改为"p"以找到最大的一个。
功能完成后,"maxPrint"突然又变成了0...在那之后,maxPrint甚至没有在任何地方使用。
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const char duomF[] = "1.txt";
const char rezF[] = "rez1.txt";
const int CMax = 81;
void reset(int SK[])
{
for (int i = 0; i < CMax; i++)
{
SK[i] = 0;
}
}
void skaitymas(int SK[], int &n, int &maxPrint)
{
ifstream df(duomF);
char temp;
int tempsk;
int p;
df >> n;
for (int i = 0; i < n; i++)
{
df >> p;
if (p > maxPrint)
{
maxPrint = p;
}
cout << p << " " << maxPrint << endl;
for (int j = CMax - p; j < CMax; j++)
{
df >> temp;
{ if (temp == '0') tempsk = 0;
else if (temp == '1') tempsk = 1;
else if (temp == '2') tempsk = 2;
else if (temp == '3') tempsk = 3;
else if (temp == '4') tempsk = 4;
else if (temp == '5') tempsk = 5;
else if (temp == '6') tempsk = 6;
else if (temp == '7') tempsk = 7;
else if (temp == '8') tempsk = 8;
else if (temp == '9') tempsk = 9;
}
SK[j] += tempsk;
}
}
df.close();
}
void skaiciavimas(int SK[])
{
int temp;
for (int i = CMax; i >= 0; i--)
{
if(SK[i] >= 10)
{
temp = SK[i] / 10;
SK[i-1] += temp;
SK[i] = SK[i] % 10;
}
}
}
int main()
{
int SK[CMax];
int n; int maxPrint = 0;
reset(SK);
skaitymas(SK, n, maxPrint);
skaiciavimas(SK);
for (int i = CMax - (maxPrint - 1); i < CMax; i++) cout << SK[i] << " ";
cout << maxPrint << endl;
ofstream rf(rezF);
for (int i = CMax - (maxPrint - 1); i < CMax; i++) rf << SK[i];
rf.close();
return 0;
}
在此循环中,您正在越界访问SK
:
void skaiciavimas(int SK[])
{
int temp;
for (int i = CMax; i >= 0; i--)
{
if(SK[i] >= 10) //<<< BUG (i = CMax)
{
temp = SK[i] / 10; //<<< BUG (i = CMax)
SK[i-1] += temp; //<<< BUG (i = 0)
SK[i] = SK[i] % 10; //<<< BUG (i = CMax)
}
}
}
请注意,SK
的有效索引是从 0
到 CMax - 1
的,因此访问SK[CMax]
会导致未定义的行为,访问SK[-1]
也是如此。
请注意,当你越界写入数组时,你可能会覆盖相邻的变量,这可能解释了maxPrint
的意外修改,但与任何未定义行为的情况一样,任何事情都可能发生。
在不知道你的代码应该做什么的情况下,我只能猜测也许你的 for 循环应该是:
for (int i = CMax - 1; i > 0; i--)
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 突然变量复位
- 变量复位"randomly"