gpt4 book ai didi

C数组链表,将一个数组链表赋值给另一个

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:18 25 4
gpt4 key购买 nike

我正在尝试用链表数组编写一个简单的字典,但在调用显示函数后我一直丢失数据。

这是我的结构定义

typedef struct node{
int elem;
struct node *next;
}*L;

typedef L Dictionary[10];

这是我的展示

void display(Dictionary A)
{
int i;
for(i=0;i<10;i++){
printf("A[%d]: ",i);
while(A[i]!=NULL){
printf("%d\t",A[i]->elem);
A[i] = A[i]->next;
}
printf("\n");
}
}

解决办法是创建一个临时变量。

我试过了

Dictionary tempStruct
for(i=0;i<10;i++){
tempStruct[i] = A[i];
}

并且有效。但是有没有比这更有效的分配链表的其他方法?

tempStruct = A;

实际上不起作用,我得到 incompatible types node** to Dictionary{*node[10]}

最佳答案

您可以将显示函数中的循环更改为:

for(i=0;i<10;i++){
printf("A[%d]: ",i);
L tmp = A[i];
while(tmp!=NULL){
printf("%d\t",tmp->elem);
tmp = tmp->next;
}
printf("\n");
}

不需要复制整个数组,一个简单的临时指针在链表中导航就足够了。

旁注:对于数组的副本,您尝试使用tempStruct = A;分配它。这不起作用的原因有两个:

  • 在您的函数中,A 没有数组类型。 C 不支持将数组 传递给函数。当一个函数有一个数组类型的参数时,它会自动调整为指针类型,而不是传递一个数组,而是传递一个指向数组第一个元素的指针。这种效果通常表示为数组衰减为指针,这就是您将 incompatible types node** to Dictionary{*node[10]} 消息的原因。

  • 即使 A 数组类型,它仍然无法工作,因为 C 不允许分配给一个大批。这有点令人惊讶,因为同样的事情也适用于 struct。我想不出在 C 中不允许分配数组的充分理由,你应该记住你不能。当然,你可以手动完成,如果你不想分配每个元素,你可以使用函数 memcpy() , 在 string.h 中声明:

    int foo[5];
    int bar[5] = {1, 2, 3, 4, 5};

    // instead of foo = bar;
    memcpy(foo, bar, sizeof foo);

与您的问题无关,但我很难理解这段代码。您的 typedef 的可读性是灾难性的。 永远不要将指针隐藏在typedef 之后——为了理解处理指针的代码,指针显而易见 很重要。数组类型的 typedef 至少也是有问题的。我建议使用以下代码:

typedef struct node {
int elem;
struct node *next;
} node;
// not strictly necessary, but IMHO, if you want to typedef a struct type,
// it's the least confusing option to name it the same as the struct tag.

#define DICTSIZE 10

void display(node **a) // variable names are often lowercase by convention
{
// to cope with ANY possible size, you need size_t, int might be too small
// include stddef.h or stdlib.h to use it. Of course, with 10 elements,
// int is enough.
for (size_t i = 0; i < DICTSIZE; ++i) {
printf("a[%zu]: ", i);
node *tmp = a[i];

// now it's obvious tmp is a pointer, so no need to explicitly
// write the != NULL ... (any pointer that's not NULL evaluates true)
while (tmp) {
printf("%d\t", tmp->elem);
tmp = tmp->next;
}
printf("\n");
}
}

还要注意一些添加的空格如何极大地提高代码的可读性(因此,请使用它们)。


我认为您的原始显示功能已损坏,因为它修改了它显示的内容。这不是显示 数据的函数的预期行为。如果您想进一步改进您的代码,您应该使用 const 来明确表示该函数不应修改它接收到的内容,以便编译器可以捕获错误。在上面的示例中,display 的签名最好如下所示:

void display(const node *const *a)

第一个 const 将使任何 struct node 不可变,第二个 const(在星号之后)使数组中的指针不可变。有了这个,你还必须写

    const node *tmp = a[i];

因为您不能将 const 指针分配给非常量指针。

关于C数组链表,将一个数组链表赋值给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45654764/

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