将指针传递给结构数组

时间:2018-01-23 01:41:06

标签: c pointers

我遇到了一直在处理的书籍分配问题,希望得到一些帮助。我的程序没有问题编译,但是当我运行它时,我得到了

First time through: (null)
After: 0000000
First time through: (null)
After: 1111111

当我插入哈希时,它会检查是否已分配该数组值。如果是,则打印“检测到碰撞”并创建新节点并将其链接到上一个节点。现在它看起来像是一个自动变量,即使我传给它一个指针?

我很确定它与我如何声明我的结构数组并将它们传递给insert_hash有关,但我似乎无法弄明白。任何帮助表示赞赏!

struct hash_node
{
    char *data;
    struct hash_node *next;

};

struct hash_node *create_table(int size);
unsigned int hash(const char *str);
void insert_hash(const char *str, const char *value, struct hash_node *h);

int
main(void)
{   
    struct hash_node *table = create_table(101);

    insert_hash("testing", "0000000", table);
    insert_hash("testing", "1111111", table);


}

struct hash_node
*create_table(int size)
{
    struct hash_node *table = calloc(size, sizeof(*table));

    if(!table)
    {
        fprintf(stderr, "Unable to allocate memory\n");
        return NULL;
    }

    return table;
}

unsigned int
hash(const char *str)
{
    unsigned int c, hash;

    while ((c = *str++))
    {
        hash += c;
    }

    hash = hash % 100;

    return hash;
}

void
insert_hash(const char *str, const char *value,  struct hash_node *h)
{
    int temp = hash(str);

    printf("First time through: %s\n", h[temp].data);

    if (h[temp].data)
    {
        fprintf(stderr, "Collision detected\n");

        struct hash_node *node = calloc(1, sizeof(*node));

        if (!node)
        {
            fprintf(stderr, "Unable to allocate memory\n");
            return;
        }

        node -> data = malloc(strlen(value) + 1);
        strncpy(node -> data, value, strlen(value) + 1);

        node->next = NULL;

        h[temp].next = node;
    }
    else
    {

        h[temp].data = malloc(strlen(value) + 1);
        strncpy(h[temp].data, value, strlen(value) + 1);
    }

    printf("After: %s\n", h[temp].data);

}

1 个答案:

答案 0 :(得分:1)

hash功能错误

unsigned int
hash(const char *str)
{
    unsigned int c, hash;   //<--- not initialized

    while ((c = *str++))
    {
        hash += c;
    }

    hash = hash % 100;

    return hash;
}

hash变量已初始化,因此每个变量都有一个未定义的值 你执行它的时间。用0:

初始化它
unsigned int
hash(const char *str)
{
    unsigned int c, hash = 0;

    while ((c = *str++))
    {
        hash += c;
    }

    hash = hash % 100;

    return hash;
}

然后我得到

First time through: (null)
After: 0000000
First time through: 0000000
Collision detected
After: 0000000

修改

如果发生碰撞,您也无法正确附加新节点。您 首先必须找到列表的末尾,然后在最后添加新节点 列表:

node *tail = h[temp].next;

while(tail->next)
    tail = tail->next;


struct hash_node *node = calloc(1, sizeof(*node));
...

tail->next = node;

或者您可以在列表的开头预先建立新节点

struct hash_node *node = calloc(1, sizeof(*node));
...

node->next = h[temp].next;
h[temp].next = node;