warning: assignment from incompatible pointer type for linklist array

家住魔仙堡 提交于 2019-12-22 18:25:23

问题


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


回答1:


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 :)




回答2:


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); 

}

        }   
    }
}


来源:https://stackoverflow.com/questions/30723241/warning-assignment-from-incompatible-pointer-type-for-linklist-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!