0
我敢肯定,这个错误是显而易见的,但我确定无法找到它。无法找出这个分段错误
基本上我试图通过二维数组做一个棋盘。我正在通过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(...) */
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(...)
在中被调用在下面的功能:
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
}
是的,我知道diagnol没有拼写对角线;)
D'oh! :)是的,忘了在上限上。 – d0rmLife