C哈希表seg故障问题

时间:2012-01-23 15:41:57

标签: c hashtable

我一直在尝试使用uthash.h实现哈希表,遵循(优秀)文档我已经能够使用以下代码获取添加和查找函数:

#include <stdio.h>
#include "../src/uthash.h"

struct my_struct
{
    int id;                    /* key */
    char name[10];
    double height;
    UT_hash_handle hh;         /* makes this structure hashable */
};

/* hash-table declared as a global variable */
struct my_struct *users = NULL;    /* important! initialize to NULL */

void add_user(int user_id, char *name, double height) {
    struct my_struct *s;

    s = malloc(sizeof(struct my_struct));
    s->id = user_id;
    strcpy(s->name, name);
    s->height = height; 
    HASH_ADD_INT( users, id, s );  /* id: name of key field */
}

struct my_struct *find_user(int user_id) {
    struct my_struct *s;

    HASH_FIND_INT( users, &user_id, s );  /* s: output pointer */
    return s;
}

int main()
{  
    add_user(users, 1, "ben", 1.85);

    struct my_struct *user;
    user = find_user(users, 1);

    printf("user id: %d user name: %s height: %g\n", user->id, user->name,  user->height);

    return 0;
}

这是一个好的开始,但我对将散列的头部声明为全局变量并且想要将其作为参数传递给add和find函数感到不满,例如:

#include <stdio.h>
#include "../src/uthash.h"

struct my_struct
{
    int id;                    /* key */
    char name[10];
    double height;
    UT_hash_handle hh;         /* makes this structure hashable */
};

void add_user(struct my_struct *users, int user_id, char *name, double height) {
    struct my_struct *s;

    s = malloc(sizeof(struct my_struct));
    s->id = user_id;
    strcpy(s->name, name);
    s->height = height; 
    HASH_ADD_INT( users, id, s );  /* id: name of key field */
}

struct my_struct *find_user(struct my_struct *users, int user_id) {
    struct my_struct *s;

    HASH_FIND_INT( users, &user_id, s );  /* s: output pointer */
    return s;
}

int main()
{
    /* hash_table declared as a local variable and passed in as a parameter to
     * add_user and find_user functions */
    struct my_struct *users = NULL;    /* important! initialize to NULL */

    add_user(users, 1, "ben", 1.85);

    struct my_struct *user;
    user = find_user(users, 1);

    printf("user id: %d user name: %s height: %g\n", user->id, user->name,  user->height);

    return 0;
}

此版本在printf上导致SEG错误,看起来没有任何内容添加到哈希表中。无法真正看到第二个版本出错的地方。当然不能要求将所有哈希表声明为全局变量以使其起作用吗?

可能错过了一些明显的东西 - 但我看不出它是什么......

1 个答案:

答案 0 :(得分:4)

如果要修改函数内的指针,则必须使用其地址 所以,功能

add_user(struct my_struct *users, int user_id, char *name, double height)

必须是

add_user(struct my_struct **users, int user_id, char *name, double height)

如果没有,指针不会被修改。

当然,在add_user内使用

HASH_ADD_INT( *users, id, s )