1

我已经在这个小项目上工作了很长一段时间,但我无法弄清楚为什么我没有得到预期的结果。我是 C 编程的初学者,所以我对指针和内存分配/释放的理解是新手。无论如何,我通过最初构建一个哈希函数,然后向它添加一个计数来构建这段代码。但是,当我测试它时,有时计数有效,有时无效。我不确定这是哈希函数的错,还是我设置计数的方式的错。文本文件一次读取一行,是一个由十六进制组成的字符串。

    struct node {
    char *data;
    struct node *next;
    int count;  /* Implement count here for word frequencies */
};

#define H_SIZE 1024
struct node *hashtable[H_SIZE]; /* Declaration of hash table */

void h_lookup(void)
{
    int i = 0;
    struct node *tmp;

    for(i = 0; i < H_SIZE; i++) {

        for(tmp = hashtable[i]; tmp != NULL; tmp = tmp->next) {
            if(tmp->data != 0) {
                        printf("Index: %d\nData: %s\nCount: %d\n\n", i,
                                 tmp->data, tmp->count);
            }
        }

    }
}


/* self explanatory */

void h_add(char *data)
{
    unsigned int i = h_assign(data);
    struct node *tmp;
    char *strdup(const char *s);


    /* Checks to see if data exists, consider inserting COUNT here */

    for(tmp = hashtable[i]; tmp != NULL; tmp = tmp->next) {

        if(tmp->data != 0) { /*  root node */
            int count = tmp->count;
            if(!strcmp(data, tmp->data))

                count= count+1;
            tmp->count = count;
                    return;
        }
    }

    for(tmp = hashtable[i]; tmp->next != NULL; tmp = tmp->next);

    if(tmp->next == NULL) { 
             tmp->next = h_alloc();
             tmp = tmp->next;
             tmp->data = strdup(data);
             tmp->next = NULL;
             tmp->count = 1;
    } else
        exit(EXIT_FAILURE); 
}

/* Hash function, takes value (string) and converts into an index into the array of linked lists) */

unsigned int h_assign(char *string)
{
    unsigned int num = 0;

    while(*string++ != '\0')
            num += *string;

    return num % H_SIZE;
}

/* h_initialize(void) initializes the array of linked lists. Allocates one node for each list by calling h_alloc which creates a new node and sets node.next to null */

void h_initialize(void)
{   int i;
    for(i = 0; i <H_SIZE; i++) {
          hashtable[i] = h_alloc();
    }

}

/* h_alloc(void) is a method which creates a new node and sets it's pointer to null */

struct node *h_alloc(void)
{
    struct node *tmp = calloc(1, sizeof(struct node));

    if (tmp != NULL){
        tmp->next = NULL;
        return tmp;
    }

    else{
        exit(EXIT_FAILURE);
    }
}

/* Clean up hashtable and free up memory */

void h_free(void)
{
    struct node *tmp;
    struct node *fwd;
    int x;

    for(x = 0; x < H_SIZE; x++) {

          tmp = hashtable[x];
          while(tmp != NULL) {
                  fwd = tmp->next;

              free(tmp->data);
              free(tmp);

              tmp = fwd;

          }
    }
}
4

1 回答 1

0

我假设计数不起作用时不会增加。strdup 可能无法为新字符串分配内存并返回 NULL。如果失败,您应该检查返回值并优雅地退出。

于 2013-10-08T04:26:22.570 回答