我有三个文件: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也是指向节点的指针。我不明白这些是怎么不相容的!
这是怎么回事?谢谢!

最佳答案

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

声明struct node但在其中使用struct Node *;C区分大小写,因此指针不是同一类型。也许不幸的是,只要你不去引用未知类型的指针(这是一个用于“不透明指针”的习惯用法),C会很高兴地让你操纵它们,所以你得到的唯一警告就是指针类型不匹配。

09-06 04:35