gpt4 book ai didi

c - "assignment from incompatible pointer type [enabled by default]"?

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

我是 C 语言的新手,我尝试使用这两个结构编写一个在列表开头插入节点的函数:

typedef struct singly_linked_list_node {
char *data;
struct singly_linked_list_node *next;
} node;

typedef struct singly_linked_list_head {
struct node *first;
struct node *last;
int size;
} sin_list;

我的职能是

void insert_at_start(sin_list* list, char *str)
{
int length;
node *newnode;
newnode = malloc(sizeof(node));
length = strlen(str) + 1;
newnode->data = malloc(sizeof(length));
strcpy(newnode->data, str);
newnode->next = list->first;
list->first = newnode;
if (list->last == NULL) list->last = newnode;
}

当我编译时,我在最后 3 行收到警告“来自不兼容指针类型的赋值 [默认启用]”,所以显然我遗漏了一些东西。

最佳答案

通过 struct singly_linked_list_head 的定义,您可以对 struct 类型使用两个隐式前向声明。这些是

struct node *first;
struct node *last;

此外,您还有 节点 的类型定义。 struct node 类型永远不会解析,但只要您只使用指向它的指针,编译器就可以接受。在 C 语言中,结构名称和类型定义有两个不同的 namespace 。

通过使用您的 typedef 修复您的代码:

typedef struct singly_linked_list_head {
node *first;
node *last;
int size;
} sin_list;

EDIT 当你分配内存时,你应该使用 str 的长度而不是变量 length 的大小来分配内存数据:

length = strlen(str) + 1;
newnode->data = malloc(sizeof(length));

更改为:

length = strlen(str) + 1;
newnode->data = malloc(length);

关于c - "assignment from incompatible pointer type [enabled by default]"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27999811/

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