如何自动更改变量的赋值

How the assigned value to variable gets changed automatically?

本文关键字:赋值 变量 改变 何自动      更新时间:2023-10-16

当我为std::cin >> diff;提供输入时,它取输入值,当我输入数组的值时,diff变量的值会发生变化,并设置数组的4th element的值。请帮我哪里出了问题。我试过fflush(std)。但这对我没有帮助。

我正在使用Visual Studio 2010 Ultimate edition

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    int i, num;//[]={0};
    int diff = 0;
    int numset[] = {0};
    int temp, cnt;
    cnt = num = i = 0;
    std::cout << "Enter your number and difference : ";
    //fflush(stdin);
    std::cin >> num ;
    std::cin >> diff;
    cout << "Enter array Elements : n";
    for(i = 0; i < num; i++)
    {
        cin >> numset[i];
        //fflush(stdin);
    }
    for(i = 0; i < num; i++)
    {
        for(int j = i; j < num; j++)
        {
            if(i == j)
            {
                temp = numset[j];
            }
            else
            {
                if((diff == (numset[j] - temp)) || (((-1)*diff) == (numset[j] - temp)))
                {
                    cnt++;
                }
            }
        }
    }
    cout << cnt << endl;
    system("pause");
    return 0;
}

您的访问超出了数组numset的范围,因此您的代码具有未定义行为(UB),任何事情都可能发生。它可能会覆盖堆栈上的变量(就像在您的情况下一样),可能会崩溃,可能会在线订购披萨。

numset被声明为单个元素数组,因此对i > 0访问numset[i]会导致UB。您可能应该将numset更改为std::vector<int>,并使用push_back()向其添加数字。