C语言 为什么我在这里收到不兼容的指针类型警告?



我在这里使用链表实现了一个非常基本的堆栈作为练习。

我的程序有以下三个文件。

堆栈.h

#ifndef STACK_H
#define STACK_H
#include <stdio.h>
struct Node {int content; struct node *next;};
void push(struct Node **node, int i);
int pop(struct Node **node);
#endif

堆栈.c

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void push(struct Node **node, int i)
{
struct Node *new_node = malloc(sizeof(struct Node));
if (!(*node)){
(*new_node).content = i;
(*new_node).next = NULL;
*node = new_node;
return;
}
(*new_node).content = i;
(*new_node).next = (struct Node *)*node;
*node = new_node;
return;
}
int pop(struct Node **node)
{
if (*node == NULL){
printf("Stack is emptyn");
exit(EXIT_FAILURE);
}
struct Node *temp = (**node).next;
int i = (**node).content;
free(*node);
*node = temp;
return i;
}

主.c

#include <stdio.h>
#include "stack.h"
struct Node *top = NULL;
int main(void)
{
push(&top, 2);
printf("%dnn", pop(&top));
return 0;
}

但是,当我编译它时,我收到以下警告

stack.c: In function ‘push’:
stack.c:18:19: warning: assignment from incompatible pointer type
(*new_node).next = (struct Node *)*node;
^
stack.c: In function ‘pop’:
stack.c:31:22: warning: initialization from incompatible pointer type
struct Node *temp = (**node).next;
^

尽管程序不顾这些警告运行并给出正确的输出,但我仍然想了解为什么会发生这种情况。

为什么我会收到这些警告?我该如何解决它们?

由于本声明中的拼写错误

struct Node {int content; struct node *next;};
^^^^                      ^^^^

声明了两种类型struct Nodestruct node是不兼容的类型。

至于函数,那么它们可以简单地定义。例如,可以通过以下方式声明函数push

int push( struct Node **node, int i )
{
struct Node *new_node = malloc( sizeof( struct Node ) );
int success = new_node != NULL;
if ( success )
{
(*new_node).content = i;
(*new_node).next = *node;
*node = new_node;
}
return success;
}

此外,如果堆栈为空,退出程序也是一个坏主意。您还应该重写函数pop

例如,函数可以像

int pop( struct Node **node, int *i );

如果堆栈为空,则函数返回0。否则,它将返回1并在表达式中*i节点的值。

相关内容

最新更新