我在运行时收到分段错误,并且不知道原因。
它应该能够从文件中读取每个字符串,并使用qsort
将单词排序到表中作为键。每个键都应该挂起一个链接列表,用于存储具有相同排序表示的常规单词。
一旦用户输入一个字符串,它就会对其进行排序,查看其排序的表示,然后打印出其链接列表中具有相同排序表示的所有单词。
示例:
steak
aekst
steak
,stake
以及aekst
作为其排序表示的任何其他字词。每次运行时,都会收到“分段错误”。我不知道为什么。
int main(int argc, char **argv)
{
// variables declared
FILE *file;
char line[50];
char string[50] = {'\0'};
int quit = 0;
char* ptr;
int fullTbl = 0;
double load = 0.0;
int empty = 0;
char sort_Str[50];
int i;
int len = 0;
int pos;
int hash_Fun;
hash_table *ht;
ht = create (TABLESIZE);
// print an error message if there are not 2 arguments
if(argc != 2) {
printf("Usage: %s <input file name> \n", argv[0]);
exit(-1);
}
strcpy (line, (argv[1]));
// open the file specified by the user
if ((file = fopen(argv[1], "r")) == NULL) {
printf("File could not open!!\n");
exit(-1);
}
// check to see if the user wants a specific function
if(argc == 3){
hash_Fun = atoi(argv[2]);
}
while(fscanf(file,"%s",string) == 1) {
len = strlen(string) ;
//save originial string
for (i = 0; i < len; i++){
strcpy(sort_Str, string);
}
qsort(string, len, sizeof(char), cmp);
/*if(hash_Fun == 0)
pos = hash_0(string, ht);
else
pos = hash_1(string, ht);*/
/*insert(string, sort_Str, pos, &fullTbl);*/
insert(string, ht);
insert(sort_Str, ht);
/*load = (double)fullTbl / (double)TABLESIZE;
if(load > CONSTANT){
//call the resize function
hashTable_resize(&(*ht), TABLESIZE);
}
empty = TABLESIZE - fullTbl;*/
}
/*printf("Filled buckets: %d", fullTbl);
printf("\nLoad factor: %.3f", load);
printf("\nEmpty buckets: %d", empty);*/
fclose(file);
/* Interactive loop that asks the user to enter a string, then sort*/
while(!quit) {
printf("\n\nEnter a word that you would like: ");
fflush(stdout);
if (fgets(string, sizeof (string), stdin) != NULL) {
ptr = strchr(string, '\n');
if (ptr != NULL)
*ptr = '\0';
if ((string[0] == 'q' || string[0] == 'Q') && string[1] == '\0')
quit = 1;
else {
len = strlen(string);
for (i = 0; i < len; i++){
strcpy(sort_Str, string);
}
qsort(string, len, sizeof(char), cmp);
// check to see which hash function to sort by
/*if(hash_Fun == 0)
pos = hash_0(string);
else
pos = hash_1(string);*/
if (search(sort_Str, ht) != NULL)
printf("\n");
else
printf("Word is not in the dictionary\n");
}
}
}
// free the hash table
free_hash(ht);
return 0;
}