gpt4 book ai didi

c - 打印答案时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:24:22 24 4
gpt4 key购买 nike

我刚刚对树进行了一些练习,并且不明白为什么当我尝试将 vcard 插入到我的二叉搜索树中时,我总是遇到段错误...有什么帮助吗?谢谢。我已附加该函数以及用于运行该函数的一些测试。由于某种原因,它适用于一种情况(当我将 ID2 与 bst 匹配时),但当我尝试将 ID1 与 bst 匹配时则不起作用。

谢谢!

typedef struct {
char *cnet;
char *email;
char *fname;
char *lname;
char *tel;
} vcard;

typedef struct bst bst;
struct bst {
vcard *c;
bst *lsub;
bst *rsub;
};

int bst_insert(bst *t, vcard *c) {

if (t->c == NULL) {
fprintf (stderr, "Empty vcard");
}
if (strcmp(c->cnet,t->c->cnet) == 0) {
return 0;
}
else if ((strcmp(c->cnet,t->c->cnet) < 0) && (t->lsub == NULL)) {
t->lsub->c = c;
return 1;
}
else if ((strcmp(c->cnet, t->c->cnet) < 0) && (t->lsub != NULL)) {
bst_insert(t->lsub, c);
}
else if ((strcmp(c->cnet, t->c->cnet) > 0) && (t->rsub == NULL)) {
t->rsub->c = c;
return 1;
}
else if ((strcmp(c->cnet, t->c->cnet) > 0) && (t->rsub != NULL)) {
bst_insert(t->rsub, c);
}

}

int main () {
vcard NewID;
NewID.cnet = "leeholim";
NewID.email = "leeholim@uchicago.edu";
NewID.fname = "leeho";
NewID.lname = "lim";
NewID.tel = "555-555-5555";


vcard NewID2;
NewID2.cnet = "donalfonsodailey";
NewID2.email = "ddailey@gmail.com";
NewID2.fname = "My name's donny";
NewID2.lname = "dailey";
NewID2.tel = "212-323-1234";


bst ID;
ID.c = &NewID;
ID.lsub = NULL;
ID.rsub = NULL;

printf("%s\n", Poop->c->fname);
printf("%d\n", bst_insert(&ID, &NewID2));
}

最佳答案

else if ((strcmp(c->cnet,t->c->cnet) < 0) && (t->lsub == NULL)) {
t->lsub->c = c;
return 1;
}

t->lsub == NULL时,绝对不应该分配t->lsub->c

关于c - 打印答案时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446083/

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