我遇到了段错误。这确实很基本,但我不知道如何。
根据我的理解,这就是我正在做的事情:
我创建了一个名为节点的结构。一个节点有两个值:字符串 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/