我正在为我的 C 类入门编写一个程序,该程序要求我根据我的教授提供的字典文本文件编写一个程序来解决拼图(你知道,就是你在报纸上看到的那些字谜)给我们。它按字母顺序排列字典中的单词,从文本文件(称为“jumble.txt”)中提取困惑,按字母顺序排列这些单词,然后运行字符串比较以找到匹配项。我已经编写了所有代码,但是当我尝试运行它时它立即崩溃了,我不明白为什么。我想也许 Stackoverflow 用户可以帮我解决这个问题。
这是我的代码:
#include <stdio.h>
#include <strings.h>
#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000
typedef struct {
char word[MAX_WORD_LEN+1];
char sort[MAX_WORD_LEN+1];
} jumble_type;
void bubblesort(char letters[], int length);
int main () {
int words, jumbles;
int j, q;
jumble_type list[MAX_NUM_WORDS];
jumble_type list2[MAX_NUM_WORDS];
// Creating file pointers
FILE *ifp;
FILE *ifp2;
//Opens Jumble and dictionary files and reads the info from them
ifp = fopen("jumbledct.txt", "r");
ifp2 = fopen("jumble.txt", "r");
//Assigns the value of "words" to the first line of jumbledct.txt
fscanf(ifp, "%d", words);
//Assigns the value of "jumbles" to the first line of jumble.txt
fscanf(ifp2, "%d", jumbles);
// Reads the words from the dictionary into the "word" section of our
// list structure.
int i;
for (i = 0; i < words; i++){
fscanf(ifp, "%s", &list[i].word);
strcpy(list[i].sort, list[i].word);
bubblesort(list[i].sort, strlen(list[i].sort));
printf("%s\n", list[i].sort);
}
//Reads from Jumble.txt
for (i = 0; i < jumbles; i++){
fscanf (ifp2, "%s", &list2[i].word);
strcpy(list2[i].sort, list2[i].word);
bubblesort(list2[i].sort, strlen(list2[i].sort));
//printf("%s\n", list2[i].sort);
}
for(j=0;j<jumbles; j++){
printf("JUMBLE PUZZLE # %d: %s\n", j+1, list2[j].word);
int x=0;
for (q = 0; q < words; q++){
if(strcmp(list2[j].sort, list[q].sort)==0){
printf("%s\n", list[q].word);
x++;
}
}
if (x == 0){
printf("Sorry, this puzzle has no solutions. \n\n");
}
printf("\n");
}
return 0;
}
void bubblesort(char letters[], int length) {
char temp;
int x, y;
for(x = 0; x < length; x++){
for (y = x; y < length; y++){
if (letters[x] > letters[y]){
temp = letters[y];
letters[y] = letters[x];
letters[x] = temp;
}
}
}
}
预先感谢您的所有帮助。
最佳答案
我的 C 有点生疏,但 fscanf 函数的第三个参数不应该是地址(如 &words 和 &jumbles)吗?
关于c - 困惑解决程序在运行时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10264270/