C 为什么这只是打印最后一个字?
我真的很难调试这个。当我试图打印出结构时,我只知道最后一个字。我是在记忆中写东西还是什么?有人能帮我吗C 为什么这只是打印最后一个字?,c,pointers,structure,C,Pointers,Structure,我真的很难调试这个。当我试图打印出结构时,我只知道最后一个字。我是在记忆中写东西还是什么?有人能帮我吗 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
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;
*/
}
}
在
insert_hash
中,您有
table -> buckets_array[index] -> key = key;
响应
也就是说,让bucket入口指向从main
传递的相同内存。代码不完整,所以我不能确定,但我敢打赌它main
可以重用word
数组,并且在每次插入后不会分配新数组。因此,table->bucket\u array[index]->key
所指向的字符串的内容被覆盖
您必须将字符串复制到新的内存块中,并让bucket条目指向该块。这是大量代码,请将问题隔离到程序的某个特定部分,您应该使用调试器或打印语句,并且还应该提供一个示例输入和输出(预期和实际)为了帮助我们更好地理解这个问题,当我使用while函数时,我使用printf来查看它正在存储的数据,它正在打印刚刚扫描进来的数据,这是正确的。使用while循环完成后,我尝试打印它
printf(“%s\n”,dictionary->bucket\u array[337]->key);printf(“%s\n”,dictionary->bucket\u array[532]->key);printf(“%s\n”,dictionary->bucket\u array[93]->key)代码>但它只是给了我最后扫描的内容。风格说明:运算符优先级有时对您有利:*(table->total)=*(table->total)+1代码>可以写为*表->总计=*表->总计+1代码>,可进一步缩减为*表->合计+=1代码>这个->
绑得很紧!。类似于(表->存储桶大小[index])=(表->存储桶大小[index])+1代码>-->表格->存储桶大小[索引]+=1
int hashfunction()
有时会返回负值,通常会将其用作数组索引。危险,威尔·罗宾逊!
p -> key = key;