混乱解决程序在运行时崩溃

时间:2012-04-22 00:38:50

标签: c arrays struct io

我正在为我的Intro to 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;
        }
    }
}
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我的C有点生疏,但fscanf函数的第三个参数不应该是一个地址(比如&amp; words和&amp; jumbles)?