c - 我有一个节点哈希表。如何打印哈希表中每个节点的每个单独值?

标签 c hashtable

我遇到了段错误。这确实很基本,但我不知道如何。

根据我的理解,这就是我正在做的事情:

  • 我创建了一个名为节点的结构。一个节点有两个值:字符串 WORD 和指针 NEXT。

  • 我制作了一个表,它是两个节点的数组。

  • node1 的值 WORD 等于“Goal”。 node2 的 WORD 值等于“Jonas”。

  • 我尝试打印两个节点的值 WORD。

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    int main(void)
    {
        typedef struct node
        {
            char word[50];
            struct node *next;
        } node;
    
        node *table[2];
    
        strcpy(table[0]->word, "Goal");
        strcpy(table[1]->word, "Jonas");
    
        printf("%s\n", table[0]->word);
        printf("%s\n", table[1]->word);
    
    }
    

在我看来,这就是我想做的:

表:

________________
|        |      |
| "Goal" | NULL | -> this is node1
|________|______|
|        |      |
|"Jonas" | NULL | -> this is node2
|________|______|

最佳答案

以下是我纠正错误的两种方法:

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


int main(void)
{
    typedef struct node
    {
        char word[50];
        struct node *next;
    } node;

    node table[2];

    strcpy(table[0].word, "Goal");
    strcpy(table[1].word, "Jonas");

    printf("%s\n", table[0].word);
    printf("%s\n", table[1].word);
}

或者使用 malloc():

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


int main(void)
{
    typedef struct node
    {
        char word[50];
        struct node *next;
    } node;

    node *table[2];

    table[0] = malloc(sizeof *table[0]);
    table[1] = malloc(sizeof *table[0]);

    table[0]->next = NULL;
    table[1]->next = NULL;


    strcpy(table[0]->word, "Goal");
    strcpy(table[1]->word, "Jonas");

    printf("%s\n", table[0]->word);
    printf("%s\n", table[1]->word);

    free(table[0]);
    free(table[1]);
}

关于c - 我有一个节点哈希表。如何打印哈希表中每个节点的每个单独值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634834/

相关文章:

c++ - 使用蒙特卡罗方法多线程计算 pi 值

c - 如何检查方阵主对角线的元素是否相同?

c - FTP 实现 : close data socket every time

c - 使用 fprintf 引起的无限循环

CS50 - 加载 - 尝试执行加载时从无处获取随机字符

java - 我们可以在 Java 的 Hashtable 中创建一对 (a,b) 作为值吗

c - 不调用地址,但 float 返回 0.000-

comparison - 哈希表的相等谓词

hashmap - 哈希表的空间复杂度是多少?

java - HashMap 不会按照默认值重新哈希