0

我有三个文件:stack2.h、stack2.c 和 main.c。

stack2.h 包含以下内容:

/* Define linked list structure */
typedef struct node {
    int val;
    struct Node *next;
} Node, *pNode;

/* Define stack structure */
typedef struct StackType {
    pNode top;
} Stack, *pStack;

/* Declare functions */
pStack InitStack( );

int IsEmpty( pStack pS );
int Pop( pStack pS );

void Push( pStack pS, int val );
void KillStack( pStack pS );

stack2.c 包含

pStack InitStack( ) {

    /* Declare variables */
    pStack pS = (pStack)malloc( sizeof(Stack) );

    /* Set first node to NULL */
    pS -> top = NULL;

    /* Return pointer to stack */
    return pS;

}

int IsEmpty( pStack pS ) {

    return ( pS->top == NULL );

}

int Pop( pStack pS ) {

    /* Declare variables */
    int ret = 0;
    pNode temp = NULL;

    /* Check if stack is empty */
   if( IsEmpty( pS ) ) {
        printf( "[ERROR] Pop operation on an empty stack.\n" );
        exit( 1 );
    }

    /* Find return value (last in) */
    ret = pS->top->val;
    temp = pS->top;

    /* Delete and kill node */
    pS->top = pS->top->next;
    free( temp );

    /* Return */
    return ret;

}

void Push( pStack pS, int val ) {

    /* Allocate memory for new node */
    pNode nnew = (pNode)malloc( sizeof(Node) );

    /* Initiate node */
    nnew->next = pS->top;
    nnew->val = val;

    /* Set structure's top to new node */
    pS -> top = nnew;

}

我不会用 main.c 包含的内容给你带来负担。本质上,它包括正确的库和文件,并且只是简单地推送和弹出一些值。我收到这些警告:

assignment from incompatible pointer types

在这两行:

    nnew->next = pS->top;
    pS->top = pS->top->next;

我有点困惑。nnew 是指向节点的指针,因此 nnew->next 也是指向节点的指针。pS 是指向堆栈的指针,因此 pS->top 也是指向节点的指针。我不明白这些是如何不兼容的!

这是怎么回事?谢谢!

4

1 回答 1

4
typedef struct node {
    int val;
    struct Node *next;
} Node, *pNode;

您声明struct nodestruct Node *在其中使用;C 区分大小写,因此指针不是同一类型。structC,也许不幸的是,只要您不取消引用它们(这是用于“不透明指针”的成语),C 将很乐意让您操纵指向未知类型的指针,因此您得到的唯一警告是指针类型不匹配。

于 2012-04-25T23:24:41.200 回答