[英]How the assigned value to variable gets changed automatically?
当我为std::cin >> diff;
提供输入时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()
向其追加数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.