【问题标题】:Weird error with binary tree and a printf二叉树和 printf 的奇怪错误
【发布时间】:2014-11-16 17:30:26
【问题描述】:

这是创建节点的代码部分,假设 c = "correctword"。第一个 printf 打印“TEST correctword”。但是第二个 printf 打印“TEST TEST”,为什么会这样?从一个到另一个我只是使用了一个strcpy,pNo->item.key应该是“正确的单词”,我做错了什么?:

TNo* TNo_Create (char* c){
    TNo* pNo = malloc(sizeof(TNo));
    printf("TEST %s", c);
    strcpy(pNo->item.key, c);
    printf("TEST %s", pNo->item.key);
    pNo->item.no = 1;
    pNo->pLeft = NULL;
    pNo->pRight = NULL;
    printf("TEST %s, %d\n", pNo->item.key, pNo->item.no);
    return pNo;
}

这是结构:

typedef struct Item{
    char* key;
    int no;
} TItem;

typedef struct No{
    TItem item;
    struct No* pLeft;
    struct No* pRight;
} TNo;

【问题讨论】:

  • 另外,如果我删除前两个 printf,程序会无缘无故停止工作(在到达最后一个 printf 之前)
  • 你没有为pNo->item.key分配内存。
  • 大声笑,原来是这样……C 对不知道在做什么的人来说可能很奇怪哈哈哈谢谢!

标签: c printf binary-search-tree


【解决方案1】:

为了回答这个问题,下面是代码:

TNo* pNo = malloc(sizeof(TNo));
printf("TEST %s", c);
pNo->item.key = malloc(strlen(c)+1);
strcpy(pNo->item.key, c);
printf("TEST %s", pNo->item.key);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2020-01-05
    相关资源
    最近更新 更多