gpt4 book ai didi

c - 在哈希表上工作时出现段错误

转载 作者:行者123 更新时间:2023-12-05 01:50:50 24 4
gpt4 key购买 nike

我刚刚通过 cs50 类(class)学习 c,我刚刚了解了指针和数据结构(这非常令人困惑,请帮助)。所以我得到了一个项目,我需要制作一个哈希表,我首先尝试将一些节点添加到列表的零索引而不是立即去哈希表,并且由于某种原因我在添加时遇到段错误列表的节点。它在第 31 行(n->next = table[0]->next;)我无法理解为什么会这样。有人请帮助并提前致谢

大声笑我只是忘了添加代码

在这里

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

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

const unsigned int N = 10;
node *table[N];

for (int i = 0; i < 10; i++)
{
table[i] = NULL;
}

char *words[] = {"Hell", "Sup", "Brain", "Greek", "Mother", "Flip", "Poster", "Dark", "Apple", "Kandy"};

for (int i = 0; i < 10; i++)
{
char *wordle = words[i];

node *n = malloc(sizeof(node));
n->word = wordle;

n->next = table[0]->next;
table[0]->next = n;

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

最佳答案

您正在将所有 table 元素初始化为 NULL,稍后您尝试访问第一个(空)元素:table[0]->next。这将导致取消引用空指针,因此会出现段错误。

您需要做的是为每个条目分配一个节点:

for (int i = 0; i < N; i++) // You didn't make N constant for no reason, did you?
{
table[i] = malloc(sizeof(node));
}

编辑:

您可以通过避免重复调用 malloc()(如 @Lundin 建议的那样)来改进/优化您的代码:

node* table = calloc(N, sizeof(node));

关于c - 在哈希表上工作时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72799635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com