Home > OS >  incompatible pointer types (in C )
incompatible pointer types (in C )

Time:06-14

My list.h

typedef struct _list_object{
    void* object;
    struct _list_object* next;
}list_object;

My list.c, where I want to create a LinkedList

list_object* new_list(){
    struct list_object* linked_list = (struct list_object*) malloc(sizeof(struct list_object*));
    return linked_list;
}

But when I do it like this I get this error:

warning: incompatible pointer types returning 'struct list_object *' from a function with result type 'list_object *' (aka 'struct _list_object *') [-Wincompatible-pointer-types] return linked_list;

What am I doing wrong?

CodePudding user response:

you need to use the correct type or struct name.

list_object *new_list(void)
{
    list_object *linked_list =  malloc(sizeof(*linked_list));
    return linked_list;

or

struct _list_object *new_list(void)
{
    struct _list_object *linked_list = malloc(sizeof(*linked_list));
    return linked_list;
}

Also do not cast the result of malloc. If you have to then it means that you compile the C code using C compiler.

Use objects instead of types in sizeofs

If you know the size of the object you may use flexible array members. . It saves one allocation/free and also reduces the number of indirections.

typedef struct _list_object{
    struct _list_object* next;
    unsigned char object[];
}list_object;


list_object *new_list(size_t objectSize)
{
    list_object *linked_list =  malloc(objectSize   sizeof(*linked_list));
    return linked_list;
}

CodePudding user response:

This code:

typedef struct _list_object{
    void* object;
    struct _list_object* next;
}list_object;

defines a type named struct _list_object or list_object. Your code struct list_object uses neither of these; struct list_object is not struct _list_object.

  • Related