正如标题所说,我试图在C中进行单词搜索。但是,当我运行我所拥有的内容时,我会收到中止(核心转储)消息。
我的代码:
void lefttoright(int rowcol, char **matrix, char* find){
int i, j, k, q, len, count = 0;
len = strlen(find);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
if (matrix[i][j] == find[0]){
char* correct = malloc(sizeof(char) * 20);
for (q = j; q < rowcol; q++){
for (k = 0; k < len; k++){
if (matrix[i][q] == find[k]){
correct[k] = matrix[i][q];
}
}
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
}
free(correct);
}
else continue;
}
}
printf("%d", count);
}
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
打印
bagel
1
bagel
2
bagel
3
bagel
4
bagel
5
bagel
6
bagel
7
bagel
8
bagel
9
bagel
10
bagel
11
bagel
12
bagel
13
Aborted (core dumped)
是什么让它中止?另外,我需要做些什么来使count == 1(这个词只出现一次)?
如果需要,我的整个程序:
#include <stdio.h>
#include <stdlib.h>
#include "scanner.h"
#include <string.h>
#include <ctype.h>
char** matrixMaker(int argc, char **argv);
void displayMatrix(int rowcol, char **matrix);
void lefttoright(int rowcol, char **matrix, char* find);
int main(int argc, char **argv){
FILE *fp = fopen(argv[2], "r");
int rowcol = atoi(argv[1]);
int a, i = 0, j;
unsigned char cha;
char **matrix;
matrix = malloc( sizeof(char *) * rowcol);
for (a=0; a<20; a++)
matrix[a] = malloc( sizeof(char) * rowcol);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
cha = tolower((unsigned char)readChar(fp));
matrix[i][j] = cha;
}
}
char* find = malloc(sizeof(char) * 20);
displayMatrix(rowcol, matrix);
printf("Enter a word to find in the puzzle : \n");
scanf("%s", find);
while(find[i]){
putchar(tolower((unsigned char)find[i]));
i++;
}
lefttoright(rowcol, matrix, find);
free(matrix);
return 0;
}
void displayMatrix(int rowcol, char **matrix){
int r,c;
for (r = 0; r < rowcol; ++r){
for (c = 0; c < rowcol; ++c){
printf("%c",matrix[r][c]);
}
printf("\n");
}
}
void lefttoright(int rowcol, char **matrix, char* find){
int i, j, k, q, len, count = 0;
len = strlen(find);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
if (matrix[i][j] == find[0]){
char* correct = malloc(sizeof(char) * 20);
for (q = j; q < rowcol; q++){
for (k = 0; k < len; k++){
if (matrix[i][q] == find[k]){
correct[k] = matrix[i][q];
}
}
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
}
free(correct);
}
else continue;
}
}
printf("%d", count);
}