"从不兼容的指针类型分配[默认启用]"?

时间:2015-01-17 13:14:29

标签: c pointers struct gcc-warning

我是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行显而易见的是我缺少的东西。

1 个答案:

答案 0 :(得分:1)

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

struct node *first;
struct node *last;

此外,您有node的typedef。类型struct node永远不会被解析,但只要您只使用指向它的指针,编译器就可以了。在语言C中,结构名称和typedef有两个不同的名称空间。

使用使用你的typedef修复你的代码:

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

编辑分配内存时,应使用str的长度而不是变量length的大小来为data分配内存:

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

更改为:

length = strlen(str) + 1;
newnode->data = malloc(length);
相关问题