[英][C++]The value has changed even though a variable has never been assigned since the first declaration
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
I practice implementing DFS.我练习实施 DFS。
I tried to solve this problem .我试图解决这个问题。
sorry for dirty code抱歉脏代码
#include<iostream>
using namespace std;
int dfs(int params[4], int i, int arr[3], int sum) {
cout << "i: " << i << endl;
cout << "params[0]: " << params[0] << endl << endl;
if (i == 4) {
if (sum == 7) {
cout << params[0];
for (int x = 1; x < 4; x++) {
if (arr[x]) {
cout << '+';
} else {
cout << '-';
}
cout << params[x];
}
cout << "=7" << endl;
exit(0);
}
return 0;
}
arr[i] = 1;
dfs(params, i + 1, arr, sum + params[i]);
arr[i] = 0;
dfs(params, i + 1, arr, sum - params[i]);
}
int main() {
string num; cin >> num;
int A = num[0] - '0';
int B = num[1] - '0';
int C = num[2] - '0';
int D = num[3] - '0';
int params[4] = {A, B, C, D};
int arr[3];
dfs(params, 1, arr, A);
}
The params[0] is declared as the first number of input. params[0] 被声明为输入的第一个数字。
And I never changed the value.而且我从来没有改变过这个值。
But when I get the value, sometimes it changes.但是当我得到值时,有时它会改变。
input输入
1222
output(This is no problem)输出(这没问题)
$ ./c
1222
i: 1
params[0]: 1
i: 2
params[0]: 1
i: 3
params[0]: 1
i: 4
params[0]: 1
1+2+2+2=7
input2输入2
0290
output2输出2
$ ./c
0290
i: 1
params[0]: 0
i: 2
params[0]: 0
i: 3
params[0]: 0
i: 4
params[0]: 1
i: 4
params[0]: 0
i: 3
params[0]: 0
i: 4
params[0]: 1
i: 4
params[0]: 0
i: 2
params[0]: 0
i: 3
params[0]: 0
i: 4
params[0]: 1
1-2+9+0=7
input3输入3
3242
output3输出3
3242
i: 1
params[0]: 3
i: 2
params[0]: 3
i: 3
params[0]: 3
i: 4
params[0]: 1
i: 4
params[0]: 0
0+2+4-2=7
The value of params[0] should always stay. params[0] 的值应始终保持不变。
Even if I change the type int
to const int
, the outputs didn't change.即使我将类型int
更改为const int
,输出也没有改变。
Why this happened?为什么会这样?
The array arr
has only 3 elements, so arr[3]
is out-of-range and no read and write to there are allowed.数组arr
只有 3 个元素,因此arr[3]
超出范围并且不允许对其进行读取和写入。 It seems params
is happened to be placed just after arr
and writing to arr[3]
is breaking data in params
.似乎params
恰好放在arr
之后,写入arr[3]
会破坏params
数据。
To easily fix this, allocate one more element for arr
.要轻松解决此问题,请为arr
再分配一个元素。
Better fix is to fix range of i
not to cause this out-of-range access.更好的解决方法是修复i
范围,以免造成这种超出范围的访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.