【发布时间】:2015-01-17 13:14:29
【问题描述】:
我是 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 行的警告“来自不兼容指针类型的赋值 [默认启用]”,所以很明显我缺少一些东西。
【问题讨论】:
-
node和list的类型不匹配
-
顺便说一句
newnode->data = malloc(sizeof(length));-->newnode->data = malloc(length); -
为什么需要struct singly_linked_list_head
-
struct node *first; struct node *last;-->node *first; node *last; -
@user7 我需要一个指向列表第一个节点的指针,一个指向最后一个节点的指针和一个 int 大小,以便打印列表中“项目”/节点的数量
标签: c pointers struct gcc-warning