gpt4 book ai didi

c - 使用 typedef 的链表

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:10 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
int value;
struct node* next;
} node;

void print(node* list);

int main()
{
node* n1;
node* n2;
n1 = (node *) malloc(sizeof(node));
n2 = (node *) malloc(sizeof(node));

n1->value = 4;
n1->next = n2;
n2->value = 5;
n2->next = NULL;

print(n1);
return 0;
}

void print(node* list)
{
node* p;
p = list;
while (p != NULL)
{
printf("%d ", p->value);
p = p->next;
}
}

代码有效,但我的编译器 (gcc) 发出警告 n1->next = n2 is (assignment from incompatible pointer type)这是什么意思?我该如何避免?

最佳答案

typedef struct {...} nodenode 声明为 struct 的类型别名 没有标签。在 C 中,两个其他方面相同的 struct 具有不同的标签不是相同的结构。 (此外,没有标记的 struct 的两个声明是不同的 struct。)该声明根本没有声明 struct node。所以 struct node* next; 指的是一个不同的、不完整的 struct。 (没关系,它不完整,因为您只将它用作指针。)

这里有一个更好的方法。 (将 node 更改为 Node 只是我的风格;当类型名称很容易与变量名称区分开来时,我发现它更容易。)注意 typedef 的预声明,它允许它的使用在后面的结构定义中。 (当它在定义中使用时它仍然不完整,但这没关系,因为它是一个指针。)

我还更改了 malloc 调用以使用正在定义的变量的类型而不是类型名,这通常是更好的样式。 (而且我删除了不必要的转换;如果您打算使用 C++,则应该将 malloc 更改为 new 而不是添加 C 风格的转换。)

#include <stdio.h>
#include <stdlib.h>

typedef struct Node Node;
struct Node {
int value;
Node* next;
};

void print(Node* list);

int main()
{
Node* n1 = malloc(sizeof *n1);
Node* n2 = malloc(sizeof *n2);

n1->value = 4;
n1->next = n2;
n2->value = 5;
n2->next = NULL;

print(n1);
return 0;
}

void print(Node* list)
{
Node* p;
p = list;
while (p != NULL)
{
printf("%d ", p->value);
p = p->next;
}
}

(在 coliru 直播)

关于c - 使用 typedef 的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42611434/

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