简体   繁体   中英

How the assigned value to variable gets changed automatically?

When I am providing input for std::cin >> diff; it takes the input value, and the moment I am entering the value of array, the diff variables value gets changed and sets the value of 4th element of the array. Please help me where is it going wrong. I have tried with fflush(std) . But it did not help me.

I am using 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;
}

You're accessing beyond the bounds of the array numset , so your code has Undefined Behaviour (UB) and anything could happen. It could overwrite variables on stack (as it does in your case), it could crash, it could order pizza online.

numset is declared as a single-element array, so accessing numset[i] for i > 0 results in UB. You should probably change numset to be a std::vector<int> and use push_back() to append numbers to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM