-1

我只是尝试使用 GCC 编译器在 C 中实现链表,但我收到了这些警告。我得到的大多数警告都是“来自不兼容的指针类型的赋值”:

linklist.c: In function 'insertatbegin':
linklist.c:20:8: warning: assignment from incompatible pointer type [enabled by default]
linklist.c:24:18: warning: assignment from incompatible pointer type [enabled by default]
linklist.c:25:8: warning: assignment from incompatible pointer type [enabled by default]
linklist.c: In function 'display':
linklist.c:37:7: warning: assignment from incompatible pointer type [enabled by default]

运行代码后,我什么也没得到。

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
typedef struct 
{
int data;
struct node *next;
}node;
void insertatbegin(node **head,int item)
{
    node *nextnode=(node *)malloc(sizeof(node));
    if(nextnode!=NULL)
    {
        nextnode->data=item;
        nextnode->next=head;   //warning line 24
        head=nextnode;      // warning line 25
    }
    else
        printf("memory not allocated\n");

}

void display(node * head)
{
    node *temp=head;
    while(temp!=NULL)
    {
        printf(" %d  ",temp->data);
        temp=temp->next;   //warning line 37
    }
}

void main()
{
    node *head=NULL;

    insertatbegin(&head,20);
    insertatbegin(&head,30);
    insertatbegin(&head,40);
    display(head);
    getch();
}

这似乎是正确的,但我没有得到任何输出。

4

1 回答 1

1

你显示typedef

typedef struct 
{
int data;
struct node *next;
}node;

在这里,您有一个typedef名为的未标记结构类型node和一个不相关的标记结构类型struct node(其详细信息未在您显示的代码中定义)。

你需要:

typedef struct node
{
    int data;
    struct node *next;
} node;

现在nodestruct node指同一类型。请记住,typedef为另一种类型引入别名;它没有引入不同的类型。

由于您在此处代码中标记为 24 的行是所示代码中的第 16 行,因此很难知道第 20 行的真正位置。在第 20 行收到警告的原因并不明显:

linklist.c:20:8: warning: assignment from incompatible pointer type [enabled by default]
linklist.c:24:18: warning: assignment from incompatible pointer type [enabled by default]
linklist.c:25:8: warning: assignment from incompatible pointer type [enabled by default]

第 24 和 25 行的警告是因为您有:

nextnode->next=head;   //warning line 24
head=nextnode;      // warning line 25

你需要:

nextnode->next = *head;   //warning line 24
*head = nextnode;      // warning line 25

这是因为headis a node **yetnextnodenextnode->nextare both node *(具有固定结构定义)。第 37 行的警告是由于struct nodevsnode混淆;如果您刚刚修复了如上所示的分配,您还会收到第 24 行的警告。

此外,正如评论中所指出的,返回类型main()应该是int,而不是void(因为这就是 C 标准所说的返回类型main())。如果您使用的是 C89 编译器(这#include <conio.h>表明您是),您应该显式地从main()函数返回一个状态。C99 及更高版本允许您省略该返回;IMNSHO,最好是明确的,并从每个声明返回值的函数中返回一个值。

另请注意,您应该在某处输出换行符;在您输出换行符之前,不能保证会显示任何内容。

于 2013-06-16T17:16:24.117 回答