【问题标题】:I have a hashtable of nodes. How to print each individual values of each node in the hashtable?我有一个节点哈希表。如何打印散列表中每个节点的每个单独的值?
【发布时间】:2018-12-05 14:44:34
【问题描述】:

我遇到了分段错误。这真的很基本,但我不知道如何。

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

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

  • 我做了一个表,它是一个由两个节点组成的数组。

  • node1 的值 WORD 等于“目标”。 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
|________|______|

【问题讨论】:

  • 你有一个指针数组。但是指针实际指向哪里?
  • 你有一个指向节点的指针数组,但是在你使用它们之前,没有一个元素被初始化为指向任何东西。
  • 我现在不需要他们指向任何东西。我做了 table[0]->next=NULL;但仍然有 SegFault。
  • 但这会取消引用指针table[0]!您不能取消引用指针,除非它指向有效的东西。也许您应该多花点时间阅读有关指针的书籍或教程?
  • 哦,好吧。我想它现在点击了!我想做那个 table[i] = malloc!非常感谢。

标签: c hashtable


【解决方案1】:

这里有两种方法可以纠正:

#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]);
}

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    相关资源
    最近更新 更多