c - 列表程序中不兼容指针类型的赋值

标签 c list pointers

我正在尝试创建一个可以在 C 中创建列表(可变长度数组)的程序,但是当我编译代码时显示“来自不兼容指针类型的赋值”错误

错误在这些行:

list_item *last = l->first;
last = last->next;
last->next = item;

代码:

typedef struct{
    struct list_item *next;
    void *data;
} list_item;

typedef struct{
    list_item *first;
    unsigned int len;
} list;

list *new_list(){
    list *l = (list *) malloc(sizeof(list));
    l->first = NULL;
    l->len = 0;
    return l;
}

list_item *new_list_item(){
    list_item *item = (list_item *) malloc(sizeof(list_item));
    item->next = NULL;
    item->data = NULL;
    return item;
}

void add_to_list(list *l, void *data){
    if(l == NULL || data == NULL){
        return;
    }

    list_item *item = new_list_item();
    item->data = data;

    int i;
    list_item *last = l->first;
    for(i = 0; i < l->len; i++){
        last = last->next;
    }   

    last->next = item;
    l->len++;
}

最佳答案

首先,在 add_to_list 中,您需要检查 l->first 是否为空(列表为空),因为稍后您尝试访问last->next,但在这种情况下,last 为空。

此外,函数 add_to_list 只接受 void* 作为数据,因此如果您想添加其他任何内容,您应该进行类型转换

例如:

add_to_list(l, (void*)4) 如果是数字或

add_to_list(l, (void*)结构某物);

关于c - 列表程序中不兼容指针类型的赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563767/

相关文章:

c - K&R 2-3 htoi 段错误

c - 仅使用程序计数器和可执行文件调查未对齐的用户空间访问

C# 按特定属性比较两个大型项目列表

java - 双向链表

c++ - 指针返回值地址

c - C 中指针的区别

python - 编辑 : how to declare array of struct in Python

C++ 新运算符返回新的意外-Dev-cpp

python - 使用反斜杠将字符串列表转换为正确的目录名称

c - 如何将整数数组分配给特定地址?