gpt4 book ai didi

c - memcpy/使用指针的链表的子列表

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

在我正在开发的遗留程序中,有几个链接列表的结构:

typedef struct Unit_Cell
{
short Type ;
char Name[x] ;
short X ;
short Y ;
struct Unit_Cell *Next;
} Unit_Cell ;

typedef struct
{
Unit_Cell *Start;
Unit_Cell *Current;
} List_Cell;

我有一个指向 List_Cell 结构的指针,其中包含所有单元格。

List_Cell *FullList; # malloc'ed,添加元素等

对于新的开发,我需要将此完整列表的子集关联到如下所示的新结构:(简化)

typedef struct Unit_NewElement
{
char Name[y];
int Value;
List_Cell *ListCells;
struct Unit_NewElement *Next;
} Unit_NewElement;

typedef struct
{
Unit_NewElement *Start;
Unit_NewElement *Current;
} List_Cell;

创建一个新元素:

Unit_NewElement *NewElement; # malloc'ed,添加元素等...
# 除了列表单元格!

循环完整的单元格列表,我正在进行计算以确定当前单元格是否需要与我的元素结构关联。

基本上,我们会做这样的事情:


# Keeping the last element
Unit_Cell *Temp = NewElement->ListCells->Current;

# Replacing last element
NewElement->ListCells->Current = FullList->Current;

# Setting temp element (which is now our previous), next pointer to the new current
Temp->Next = NewElement->ListCells->Current;

但是这样做,我实际上破坏了原始的“FullList”列表。这是我不想要的。

我需要能够从完整列表中添加单元格,为我需要的每个 NewElements,而不影响完整列表本身。

memcpy 是正确的选择吗?

memcpy(Element->ListCells->Current, FullList->Current, sizeof(Unit_Cell));

如何处理复制的结构中还有一个指针的事实?

不使用 memcpy 直接复制数据怎么样:

*Element->ListCells->Current = *FullList->Current;

谢谢

最佳答案

我认为为了获得列表的真实副本,您需要做的是 mallocmemcpy 的组合,以及复制的 Next 指针必须被覆盖。

因为我不知道你的子列表是如何创建的,所以我建议了一些东西,比如给定的起始单元格和要复制的单元格数量 - 那么你可以这样做:

ListCell *copyList(UnitCell *from, int n)
{
int i = 0;

if (!from || n <= 0)
return NULL;

ListCell *newList = (ListCell*)malloc(sizeof(ListCell));
newList->Start = NULL;
newList->Current = NULL;

while (from && i++ < n)
{
if (!newList->Start)
{
newList->Start = (UnitCell*)malloc(sizeof(UnitCell));
memcpy(newList->Start, from, sizeof(UnitCell));
newList->Current = newList->Start;
}
else if (newList->Current)
{
newList->Current->Next = (UnitCell*)malloc(sizeof(UnitCell));
memcpy(newList->Current->Next, from, sizeof(UnitCell));
newList->Current = newList->Current->Next;
}

from = from->Next;
}

// Next-pointer of last cell still points to source list cell
if (newList->Current)
newList->Current->Next = NULL;

return newList;
}

(实际上我没有测试这段代码,所以可能还有一些错误)

关于c - memcpy/使用指针的链表的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60223436/

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