C 复制链接列表中的结构

C 复制链接列表中的结构,c,C,在这里,我将结构从一个节点复制到另一个节点,但当我遇到最后一个节点时,我将出现分段错误,因为temp\u clsf->next中的memcpy将指向无效位置,我如何修复此问题?我无法释放temp\u clsf,因为它不是动态分配 while(temp_clsf!=NULL) { memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier)); if(temp_clsf->next ==NU

在这里,我将结构从一个节点复制到另一个节点,但当我遇到最后一个节点时,我将出现分段错误,因为
temp\u clsf->next
中的
memcpy
将指向无效位置,我如何修复此问题?我无法释放
temp\u clsf
,因为它不是动态分配

while(temp_clsf!=NULL)
{
    memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));
    if(temp_clsf->next ==NULL)
        return;
    else
        temp_clsf = temp_clsf->next;
}

如果,只需将副本移到
后面即可

 while(temp_clsf!=NULL)
    {
    if(temp_clsf->next ==NULL)
    return;
    //else
    memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));
    temp_clsf = temp_clsf->next;
    }

在while中使用以下条件

while(temp_clsf->next!=NULL)     

可能,
temp\u clsf->next
可能是
NULL
,因此在
memcpy

while(temp_clsf != NULL)
{
    if(temp_clsf->next == NULL)
    {
        return;
    }

    memcpy(&temp_clsf, &temp_clsf->next, sizeof(struct classifier));

    temp_clsf = temp_clsf->next;
}

更新
temp\u clsf
temp\u clsf->next
看起来像指向我的指针。因此,您的
memcpy
正在获取指针的地址并覆盖其中的内容。这是你的意图吗?不确定
sizeof(struct-classifier)
是什么,因为我们在您的示例中没有结构类型。

看起来您正在进行项目转移,可能是为了删除一个项目。如果这是一个有序数组,则无需使用
next
指针。我不确定您正在使用的其他静态分配是什么,但您只需执行以下操作即可删除单个项
temp\u clsf->next

temp_clsf->next=temp_clsf->next->next;

在循环内部,保留指向上一个节点的指针。循环结束时,使用指向NULL的指针更新该节点

/* pseudo-code */
while () {
    prev = curr;
    /* ... */
}
prev->next = NULL;

如果
temp\u clsf
本身为NULL,则该比较将尝试取消对NULL指针的引用:最好对两者进行测试:
while(temp\u clsf!=NULL&&temp\u clsf->next!=NULL)
如果我这样做,它将不会复制上一个结构,因为temp\u clsf->next将指向NULL,但是我在temp_clsf的那一瞬间拥有的数据应该复制到前面的结构中,所以memcpy应该真正复制数据而不是指针,对吗?temp\u clsf/classifier的类型结构是什么?structure1->structure2->structure3->structure4->structure5在这里,我想做一个memcpy,即如果我删除structure1,我希望输出类似structure1->structure2->structure3->structure4->structure5,但在我的代码中我删除了structure1,我希望得到这样的结构structure2->structure3->structure4->structure5,但我的代码有一个类似structure2->structure3->structure4->structure4->structure5的o/p,当它到达structure5 temp\u clsf->next时,它将为空,并且将退出循环。@cnicutar:我在这里给出了详细的解释,我被困在这个无法继续的过程中,我现在还没有得到它全部的每次删除项目时复制整个列表似乎很疯狂。我不明白你为什么不把列表的开始点改为当前第一个节点的下一个指针。。。