突然变量复位

Sudden variable reset

本文关键字:复位 变量 突然      更新时间:2023-10-16

问题:
"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的有效索引是从 0CMax - 1 的,因此访问SK[CMax]会导致未定义的行为,访问SK[-1]也是如此。

请注意,当你越界写入数组时,你可能会覆盖相邻的变量,这可能解释了maxPrint的意外修改,但与任何未定义行为的情况一样,任何事情都可能发生。

在不知道你的代码应该做什么的情况下,我只能猜测也许你的 for 循环应该是:

for (int i = CMax - 1; i > 0; i--)