C++ 本地编译的c++;代码循环不正确
以下内容在我的系统上永远不会终止C++ 本地编译的c++;代码循环不正确,c++,g++,C++,G++,以下内容在我的系统上永远不会终止 #include <iostream> using namespace std; int main(){ int solutions[1000][4] = {}; for(int a=0; 3*a<=1000; a++){ for(int b=0; 5*b<=1000; b++){ for(int c=0; 7*c<=1000; c++){
#include <iostream>
using namespace std;
int main(){
int solutions[1000][4] = {};
for(int a=0; 3*a<=1000; a++){
for(int b=0; 5*b<=1000; b++){
for(int c=0; 7*c<=1000; c++){
cout << "enter" << "\t" << a << "\t" << b << "\t" << c << endl;
if (3*a+5*b+7*c > 1000) {break;}
solutions[3*a+5*b+7*c][0] = a;
solutions[3*a+5*b+7*c][1] = b;
solutions[3*a+5*b+7*c][2] = c;
solutions[3*a+5*b+7*c][3] = 1;
cout << "exit" << "\t" << a << "\t" << b << "\t" << c << endl << endl;
}
}
}
}
我使用
g++B.cpp-ob.exe
编译了这个文件,然后只运行了可执行文件。确切的代码(已注释注销)在联机时正确终止。我的编译器版本是g++(i686-posix-dwarf-rev0,由MinGW-W64项目构建)5.3.0
。这里会出什么问题?当a=0,b=4,c=140
时,3*a+5*b+7*c
变成1000
并写入越界解决方案[1000]
时发生。似乎这种越界写入碰巧打破了循环计数器
再分配一个元素以避免这种越界写入
int solutions[1001][4] = {};
是的,就是这样。这是否意味着被覆盖的越界区域正是变量c?或者在这个未定义的写操作中发生了其他事情导致了这种情况?@eeegnu Out-Out-bound-write调用未定义的行为。对于未定义的行为,允许发生任何事情。
int solutions[1001][4] = {};