我确信这个错误很明显,但我确实很难找到它。
基本上我正在尝试通过二维数组制作棋盘。我正在通过 8 个皇后测试来测试它的功能……它不起作用。
不知何故,我的整数值之一变得异常,如图gdb
所示:
....
(gdb) cont
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
77 if (key->board[abc][bcd] == 1) {
(gdb) print abc
4424 // "SHOULD BE" ONE
(gdb) print bcd
4424 // "SHOULD BE" ONE
(gdb) backtrace
#0 0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
#1 0x08048873 in check (param1=0, param2=0) at eq1.c:91
#2 0x08048510 in recur (DEPTH=0, WIDTH=0) at eq1.c:99
#3 0x08048919 in main () at eq1.c:152
(gdb)
然后是diagnols(...)
,位于:
int recur(struct chessboard* key, int DEPTH, int WIDTH) {
/* other functions above diagnols(...) */
诊断(...):
int diagnols(int PARAMETER_ONE, int PARAMETER_TWO) { // returns 0 if good
int abc = 0;
int bcd = 0;
int counter = 0; // keeps track of conflicting piece occurrences
// OTHER CHECKS FIRST... DELETED TO SAVE ROOM
// checkign diagnol down and to the left
abc = PARAMETER_ONE+1;
bcd = PARAMETER_TWO-1;
while ( (abc>=0)&&(bcd>=0) ) {
if (key->board[abc][bcd] == 1) {
counter++;
} abc++;
bcd--;
}
// ERROR IN THIS PART
// checking diagnol down and to the right
abc = PARAMETER_ONE+1;
bcd = PARAMETER_TWO+1;
while ( (abc>=0)&&(bcd>=0) ) {
if (key->board[abc][bcd] == 1) { // ERROR
counter++;
} abc++;
bcd++;
}
return counter;
}
并在以下函数中diagnols(...)
调用:recur(...)
int check(int param1, int param2) { // if okay returns 2
// other functions
d = diagnols(param1, param2);
int total = 0;
total = (h + v + d); // if okay, equals 2
return total;
}
为了更好地衡量,这是我的结构:
struct chessboard {
int board[7][7];
};
主要:
int main() {
struct chessboard* master = malloc(sizeof(struct chessboard));
/* i set the board to zero here. used calloc() before */
recur(master, 0, 0);
// stuff
}
是的,我意识到诊断不是拼写对角线;)