用map<char, map<int, string> > Mem 类型模拟内存,数组名对应的索引的值
用map<char, int> Size 来存放数组对应的大小
假设只有未初始化和越界的错误。
即对每个表达式进行扫描,从里到外依次检验每个数组是否越界,是否未初始化。如果只有数组,则最外面的数组是声明,如果是赋值表达式,那么就不是声明。每次到声明就把数组名和对应的大小记下来。
</pre><pre name="code" class="cpp">#include <iostream>
#include <vector>
#include <sstream>
#include <map>
#include <cstdlib>
using namespace std;
typedef map<char, map<int, string> > Mem;
typedef map<char, int> Size;
Mem mem;
Size siz;
bool bug(const string &s, bool declare, string &val, string assignment = "-") {
int pos = s.find_last_of('['), idx;
if (pos == string::npos)val = s;
else idx = atoi(s.substr(pos + 1, s.find_first_of('[') - pos - 1).c_str());
for (int i = pos; i >= 0; i--) {
if (s[i] != '[') {
if (i == 0 && declare == true) { //如果是声明
siz[s[i]] = idx;
}else {
if (idx >= siz[s[i]] || idx < 0)return true; //越界
if (i == 0 && declare == false && assignment != "-")mem[s[i]][idx] = assignment; //如果不是声明且是赋值
if (mem[s[i]].count(idx) == 0)return true; //未初始化
val = mem[s[i]][idx]; //模拟访存
idx = strtol(mem[s[i]][idx].c_str(), NULL, 10);
}
}
}
return false;
}
bool debug(string & s) {
string val; int e = s.find('=');
string rval; string c;
if (e == string::npos) { //声明语句
return bug(s, true, rval);
}
else { //赋值语句
string lhs = s.substr(0, e), rhs = s.substr(e + 1);
if (bug(rhs, false, rval)) return true; //未初始化或越界
if (bug(lhs, false, c, rval))return true; //未初始化或越界
return false;
}
}
int main() {
string s;
while (cin >> s && s != ".") {
mem.clear();
siz.clear();
int cnt = 1;
bool dbug = false;
if (debug(s)) { cout << cnt << endl; dbug = true; while (cin >> s && s != "."); continue; }
else cnt++;
while (cin >> s && s != ".") {
if (debug(s)) { cout << cnt << endl; dbug = true; while (cin >> s && s != "."); break; }
else cnt++;
}
if (dbug == false)cout << 0 << endl;
}
system("pause");
return 0;
}