我很难调试这个。当我试图打印出结构时,我只能说出最后一句话。我是在写内存还是什么?有人能帮我吗?这是为什么这只打印最后一个字?
typedef struct hash_table_ {
void **order;
int *number_next_calls;
int *number_buckets;
int *buckets_size;
int *worst;
int *total;
float *average;
int (*hash_func)(char *);
data_el **buckets_array;
} hash_table, *Phash_table;
typedef struct data_{
char *key;
void *data;
struct data_ *next;
}data_el;
main(){
while ((c = getchar()) != EOF) {
if ((c == ' ') || (c == ',') || (c == '.') || (c == '!') || (c == '"') ||
(c == ':') || (c == '\n')) {
/* End of a word */
if (char_index) {
/* Word is not empty */
word[char_index] = '\0';
lower_case_word(word);
if(!find_hash(dictionary,word)){
insert_hash(dictionary,word,frequency[hash_function(word)]);
}
printf("%s\n", dictionary -> buckets_array[hash_function(word)] -> key);
printf("%d \n",hash_function(word));
frequency[hash_function(word)]++;
char_index = 0;
num_words++;
}
}else{
word[char_index++] = c;
}
}
/*This is when it prints*/
printf("%s\n", dictionary -> buckets_array[337] -> key);
printf("%s\n", dictionary -> buckets_array[532] -> key);
printf("%s\n", dictionary -> buckets_array[93] -> key);
}
int hash_function(char *word){
int sum,i;
i = 0;
sum = 0;
while(word[i] != '\0'){
sum = sum + word[i];
i++;
}
return sum%1000;
}
void insert_hash(Phash_table table, char *key, void *data){
int index;
data_el *p, *cur;
index = table -> hash_func(key);
/*Head insertion*/
if(table -> buckets_array[index] == NULL){
table -> buckets_array[index] = (data_el *)malloc(sizeof(data_el));
table -> buckets_array[index] -> data = data;
table -> buckets_array[index] -> next = NULL;
table -> buckets_array[index] -> key = key;
}else{
printf("%s",table -> buckets_array[index] -> key);
cur = table -> buckets_array[index];
p = (data_el *)malloc(sizeof(data_el));
p -> key = key;
p -> data = data;
p -> next = cur;
cur = p;
/*
table -> buckets_array[index] = cur;
*/
}
}
这是很多代码,请将问题隔离到程序的某个特定部分,您应该使用调试器或打印语句,并且还应提供示例输入和输出(预期和实际)以帮助我们更好地理解这个问题。 – amit
那么,当我在while函数中时,我使用printf来查看它正在存储的数据,并且它正在打印刚扫描的内容,这是正确的。在完成while循环后,我尝试打印它'printf(“%s \ n”,dictionary - > buckets_array [337] - > key); printf(“%s \ n”,词典 - > buckets_array [532] - > key); printf(“%s \ n”,词典 - > buckets_array [93] - > key);'但它只是给我最后一个它扫描英寸 –
文体笔记:操作符优先有时有效地工作: *(table - > total)= *(table - > total)+ 1;'可以写成'* table - > total = * table - > total + 1;',可以进一步简化为'* table- > total + = 1;'' - >'绑定非常紧密!类似于'(table - > buckets_size [index])=(table - > buckets_size [index])+ 1;' - >>'table - > buckets_size [index] + = 1;' – wildplasser