我很難調試這個。當我試圖打印出結構時,我只能說出最後一句話。我是在寫內存還是什麼?有人能幫我嗎?這是爲什麼這隻打印最後一個字?
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