突然变量复位

xTh*_*Ec0 -3 c++

问题:
"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;

}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 5

在这个循环中,您正在访问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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,有效索引SK来自0to CMax - 1,因此访问会SK[CMax]导致未定义的行为,访问也是如此SK[-1].

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

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

for (int i = CMax - 1; i > 0; i--)
Run Code Online (Sandbox Code Playgroud)

  • 你可能会覆盖相邻的变量......或其他任何东西!从理论上讲,它可能是程序代码,操作系统代码,硬盘空间,美国宪法.未定义的行为意味着["任何事情都可能发生"](http://i123.photobucket.com/albums/o313/kasiopeia/thursday3.png) (4认同)
  • 是的.未定义的行为.幸运的是,没有猫被点燃.这次. (3认同)