gpt4 book ai didi

c - 插入哈希表时出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:38:49 25 4
gpt4 key购买 nike

我希望能够使用 getNextWord 函数返回指向文件中下一个单词的指针。我想我在插入时遇到了段错误,但我就是无法弄清楚。对此的任何帮助都会非常好。另外,我可能应该找到一种更好的方法来获取 hash_table_size,而不是增加文件中单词总数的计数然后倒带。如何让尺寸自动增长?

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

int hash_table_size;

char* getNextWord(FILE* fd) {
char c;
char buffer[256];
int putChar = 0;
while((c = fgetc(fd)) != EOF) {
if(isalnum(c)) break;
}
if(c == EOF) return NULL;

buffer[putChar++] = c;

while((c = fgetc(fd)) != EOF) {
if(isspace(c) || putChar >= 256 -1) break;

if(isalnum(c))
buffer[putChar++] = c;
}

buffer[putChar] = '\0';
return strdup(buffer);
}

struct node {
struct node *next;
int count;
char* key;
};

struct list {
struct node *head;
int count;
};

struct list *hashTable = NULL;

/*
* djb2 hash function
*/
unsigned int hash(unsigned char *str) {
unsigned int hash = 5381;
int c;

while(c == *str++)
hash = ((hash << 5) + hash) + c;

return (hash % hash_table_size);
}

struct node* createNode(char *key) {

struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
strcpy(new_node->key, key);
new_node->next = NULL;
return new_node;
}

void hashInsert(char *str) {
int hash_dex = hash(str);
struct node *new_node = createNode(str);

if(!hashTable[hash_dex].head) {
hashTable[hash_dex].head = new_node;
hashTable[hash_dex].count = 1;
return;
}

new_node->next = (hashTable[hash_dex].head);

hashTable[hash_dex].head = new_node;
hashTable[hash_dex].count++;
return;
}

void display() {
struct node *current;
int i;
while(i < hash_table_size) {
if(hashTable[i].count == 0)
continue;
current = hashTable[i].head;
if(!current)
continue;
while(current != NULL) {
char tmp[256];
strcpy(tmp, current->key);
printf("%s", tmp);
current = current->next;
}
}
return;
}

int main(int argc, char *argv[]) {

if (argc != 2) {
printf("Usage: ./hashFile textfile\n");
}
else {
FILE *file = fopen(argv[1], "r");

if(file == 0) {
printf("Could not open file\n");
}
else {

char *new_word;
while((new_word = getNextWord(file)) != NULL) {
hash_table_size++;
}
rewind(file);
hashTable = (struct list *)calloc(hash_table_size, sizeof(struct list));
while((new_word = getNextWord(file)) != NULL) {
hashInsert(new_word);
}
display();
fclose(file);
}
}
return 0;
}

最佳答案

    int c;

while(c == *str++)
hash = ((hash << 5) + hash) + c;

c 此处未初始化。就像 display 函数中的 i 一样。请启用所有编译器警告并修复它们。

另外:

char c;

char buffer[256];
int putChar = 0;
while((c = fgetc(fd)) != EOF) {
if(isalnum(c)) break;
}

c 必须是 int 类型,而不是 char

关于c - 插入哈希表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22027858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com