c - 为什么我得到这个错误的输出?

标签 c list

我创建了这个简单的双链表。 问题是,当我打印它的所有元素时,即使变量“a”每次都发生变化,它们也具有相同的 char 值。

typedef struct node{
char *name;
struct node *n;
struct node *p;
} N;

N *h=NULL;//head

void insert(char *value){
N *temp=malloc(sizeof(N));
if(h==NULL){
    h=temp;
    temp->name=strdup(value);
}
else{
    N *curr=h;
    while(curr->n!=NULL)
        curr=curr->n;
    curr->n=temp;
    temp->p=curr;
    temp->name=strdup(value);
}
}

void print(){
N *temp=h;
printf("%s\n", temp->name);
while(temp->n!=NULL){
    printf("%s\n", temp->name);
    temp=temp->n;
}
}


int main(){

char a[...];
fgets(a,...)

//there is a while section: every time i enter in it, there is:
char *input=a;
insert(input);
print();
}

所以我期望的是: 狮子 熊 山羊 .... 相反,我得到: 那么狮子 熊 那么熊 山羊 山羊 山羊

等等...

最佳答案

有几个问题。首先, print() 中有一个错误,导致最后一个值无法显示。检查 temp 而不是 temp->n:

void print()
{
    N *temp=h;

    while(temp !=NULL){
       printf("%s\n", temp->name);
       temp=temp->n;
   }
}

额外的 printf() 调用(在 while 循环之前)是第一个值被打印两次的原因。

此外,添加新节点时必须分配 p 和 n。如果您不分配它们,则不能假设它们将为 NULL。

void insert(char *value)
{
    N *temp=malloc(sizeof(N));
    if(h==NULL){
        h=temp;
        temp->p = NULL;
        temp->n = NULL;
        temp->name=strdup(value);
    }
    else{
        N *curr=h;
        while(curr->n!=NULL)
        curr=curr->n;
        curr->n=temp;
        temp->p=curr;
        temp->n = NULL;
        temp->name=strdup(value);
   }
}

另外,你需要列表是双链接的吗?您从不使用 p 指针。

关于c - 为什么我得到这个错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747358/

相关文章:

c - Windows 在释放内存时触发了断点

python - 如何使用 PyDictionary 获取单词的一种含义?

c - 结构中的二维数组 - C -

list - TCL - 带变量的列表

python - 在python中查找列表的一部分的平均值,然后修改列表

Mysql - 主键以错误的顺序列出

c# - 将未知类型的列表转换为通用列表类型

尝试从文件导入数据时崩溃

c - 如何将流 (FILE *) 与标准输出相关联?

python - C 和 Python 之间的 break 语句有区别吗?