打印答案时分段错误

时间:2015-02-11 03:27:13

标签: c segmentation-fault binary-search-tree vcard

我正在练习使用树木,并且当我尝试将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));
}

1 个答案:

答案 0 :(得分:1)

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

当然,您不应在t->lsub->c时分配t->lsub == NULL