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

时间:2017-08-23 14:38:22

标签: c list struct stack declaration

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

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

stack.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

stack.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 empty\n");
        exit(EXIT_FAILURE);
    }

    struct Node *temp = (**node).next;
    int i = (**node).content;

    free(*node);
    *node = temp;

    return i;
}

的main.c

#include <stdio.h>
#include "stack.h"

struct Node *top = NULL;

int main(void)
{
    push(&top, 2);
    printf("%d\n\n", 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;
                        ^

虽然程序运行尽管有这些警告并提供正确的输出,但我仍然想知道为什么会发生这种情况。

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

1 个答案:

答案 0 :(得分:2)

由于此声明中的拼写错误

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中返回节点的值。

相关问题