warning: assignment from incompatible pointer type for linklist array

1.1k views Asked by At

I am executing a C program where I am getting warning: warning: assignment from incompatible pointer type

I am copying related code herein:

//Structure I am using:

typedef struct graph_node
{
    int id;
    int weight;
    struct node *next;
}node, dummy;

node *head[10];

// Function which is generating this warning:
void print_list()
{
    int i;

    for (i = 0;i< vertex; i++)
    {
        printf ("\n ==>>%d ", head[i]->id);

        while (head[i]->next != NULL)
        {
            head[i] = head[i]->next;
            printf ("\t ==>>%d ", head[i]->id); /******This line is     generating warning  ********/
        }   
    }
}

Above code compiles fine with throws the warning below:

warning: assignment from incompatible pointer type for linklist array

2

There are 2 answers

0
Mohit Jain On

You should not write struct node *next; as node is not typedefed yet and struct node simply does not exist.

You should re-declare your structure as:

typedef struct graph_node
{
    int id;
    int weight;
    struct graph_node *next;
    /*     ^^^^^^           */
}node, dummy;

Why does my code compile then

When you write just struct node *next;, your compiler assumes struct node is an incomplete type (declaration only) and allows the pointer to this type.

When you convert the pointer of type struct node to node (which is a typedef of struct graph_node), the incompatible pointer conversion warning occurs to warn you from any strict aliasing rule break or similar other issues.

Is assuming struct node to be an incomplete type is little broad and a separate question.

And yes, the warning is being thrown for the line head[i] = head[i]->next; and not the next one :)

0
suren On

check this code.i think it will probably work.and post the complete code so i can resolve complete.

 typedef struct graph_node
{
    int id;
    int weight;
    struct node *next;
}node, dummy;
node *head[10];

// Function which is generating this warning:

void print_list()
{
int i;
    for (i = 0;i< vertex; i++)
    {
        printf ("\n ==>>%d ", head[i]->id);
        while (head[i]->next->next != NULL)
        {
            head[i] = head[i]->next;
         printf ("\t ==>>%d ", head[i]->id); 
               if(head[i]->next==NULL)
{
            printf ("\t ==>>%d ", head[i]->id); 

}

        }   
    }
}