简单的C trie程序出错(segmentation fault)
Simple C trie program goes wrong (segmentation fault)
为了理解尝试,我正在创建这个非常简单的 C 程序,它从用户 10 nums 从 0 到 9 作为 trie 的 children。最后一步是使用函数 print
打印此 nums,但出现分段错误:
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list *ar[10];
} list;
void insert(list *head);
void print(list *head);
int main(void)
{
printf("hello\n");
list *root = malloc(sizeof(list));
insert(root);
print(root);
}
void insert(list *head)
{
int a, i;
if (head == NULL) {
return;
}
for (i = 0; i < 10; i++) {
printf("Give Num 0-9\n");
scanf("%i", &a);
head->ar[a] = malloc(sizeof(head));
head = head->ar[a];
head->data = a;
}
}
void print(list *head)
{
if (head == NULL) {
return;
}
while (head != NULL) {
for (int i = 1; i < 10; i++) {
if (head->ar[i] != NULL) {
printf("%i", i);
head = head->ar[i];
break;
}
}
}
printf("\n");
}
您的代码存在几个问题:
第一次提到malloc
实际上并没有初始化内存(ar
字段)。你应该正确初始化它
list *root = malloc(sizeof(list));
缺少初始化,例如
root->data = 0;
for (size_t ii = 0; ii < 10; ii++) {
root->ar[ii] = NULL;
}
当您实际收集输入时,您只为 指针 分配足够的内存,而不是为实际列表本身分配内存。
head->ar[a] = malloc(sizeof(head));
应该如上初始化(head = malloc(sizeof(list)); for (size_t ...
实际上 运行 您的程序似乎存在无限循环(在纠正所有这些问题之后)。
编辑:删除 calloc
...
为了理解尝试,我正在创建这个非常简单的 C 程序,它从用户 10 nums 从 0 到 9 作为 trie 的 children。最后一步是使用函数 print
打印此 nums,但出现分段错误:
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list *ar[10];
} list;
void insert(list *head);
void print(list *head);
int main(void)
{
printf("hello\n");
list *root = malloc(sizeof(list));
insert(root);
print(root);
}
void insert(list *head)
{
int a, i;
if (head == NULL) {
return;
}
for (i = 0; i < 10; i++) {
printf("Give Num 0-9\n");
scanf("%i", &a);
head->ar[a] = malloc(sizeof(head));
head = head->ar[a];
head->data = a;
}
}
void print(list *head)
{
if (head == NULL) {
return;
}
while (head != NULL) {
for (int i = 1; i < 10; i++) {
if (head->ar[i] != NULL) {
printf("%i", i);
head = head->ar[i];
break;
}
}
}
printf("\n");
}
您的代码存在几个问题:
第一次提到
malloc
实际上并没有初始化内存(ar
字段)。你应该正确初始化它list *root = malloc(sizeof(list));
缺少初始化,例如
root->data = 0; for (size_t ii = 0; ii < 10; ii++) { root->ar[ii] = NULL; }
当您实际收集输入时,您只为 指针 分配足够的内存,而不是为实际列表本身分配内存。
head->ar[a] = malloc(sizeof(head));
应该如上初始化(
head = malloc(sizeof(list)); for (size_t ...
实际上 运行 您的程序似乎存在无限循环(在纠正所有这些问题之后)。
编辑:删除 calloc
...