Search code examples
cpointersincompatibletypeerror

type-problems in C


This may be a stupid question, and I see similar questions been asked, but I dont get the answers given. why does the following code produce:

error: incompatible types when assigning to type ‘node_t’ from type ‘struct node_t *’

node_t list_array[10];
typedef struct node
{
    int value;
    struct node *next;
    struct node *prev;
} node_t;

node_t* create_node(void)
{
    node_t *np;
    np->next = NULL;
    np->prev = NULL;
    np->value = rand() % 10;
    return np;
}

int main(void)
{
int i;
for(i = 0; i < 10; i++)
{
    list_array[i] = create_node();
}
return 0;
}    

Solution

  • Make the array into an array of pointers to fix the error, since create_node returns a pointer:

    node_t *list_array[10];
    

    Note you're not allocating any memory in create_node so using np is illegal. Try:

    node_t *np = malloc(sizeof *np);
    

    I want to make an array of node_t structs

    In that case you could leave the node_t list_array[10] and:

    • Pass &list_array[i] as an argument to the function
    • Have the function return a node_t instead of a node_t *