C堆栈指向地址?

时间:2014-02-12 17:39:45

标签: c pointers stack

我是C的新手。我已经实现了一个带有一些结构的简单堆栈,而不是。我已在下面发布了整个代码。问题部分已注释。

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

typedef struct Node{
    int data;
    struct Node *next;
} Node;
typedef struct Stack{
    Node *top;
    int size;
} Stack;

/* Function Prototypes */
void push(Stack *sPtr, int data);
int pop(Stack *sPtr);
void create(Stack *sPtr);

int main(void)
{
    static Stack first;
    create(&first);

    push(&first,4);
    push(&first,3);
    push(&first,2);

    printf("%d\n",pop(&first));
    printf("%d\n",pop(&first));
    printf("%d\n",pop(&first));
    exit(1); 
}

void push(Stack *sPtr, int data)
{
    struct Node newNode;
    newNode.data = data;
    newNode.next = sPtr->top;
    sPtr->top = &newNode;
    sPtr->size++;
    printf("%d\n",sPtr->top->data);
}
int pop(Stack *sPtr)
{
    struct Node *returnNode = sPtr->top;
    struct Node *topNode = sPtr->top;
    if(sPtr->size != 0){
        sPtr->top = topNode->next; /* =============PROBLEM?=============== */
        return returnNode->data;
    }
    else{
        printf("Error: Stack is Empty!\n");
        return -1;
    }
}
void create(Stack *sPtr)
{
    sPtr->size = 0;
    sPtr->top = NULL;
}

此代码的输出是

4
3
2
2
8103136
680997

很明显,它正在关闭顶级节点,然后打印下两个节点的地址,而不是他们的数据。

但为什么这样做呢?据我所知(这很少)预先执行此操作

sPtr->top = topNode->next;

应该告诉程序让top现在指向topNode.next。但相反,它似乎正在返回地址。这是怎么回事?

2 个答案:

答案 0 :(得分:4)

push()函数中,您正在创建一个新的struct Node并将其添加到您的堆栈中。但是,节点是push()范围内的局部变量 - 在堆栈(不是堆栈,调用堆栈)上分配,并且在push()返回时将消失。

您要做的是在上创建节点,这意味着在push()返回后它仍然存在。

由于您使用C编码,您需要执行以下操作:

struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));

由于您现在正在处理堆分配的内存,因此您需要确保在某些时候使用free()释放它(某处)。

你也没有像Jonathan所指出的那样递减size

答案 1 :(得分:3)

一个问题是pop()永远不会递减size,所以size实际上是'被推入堆栈的元素数',而不是'当前堆栈中元素的数量'。

int pop(Stack *sPtr)
{
    struct Node *returnNode = sPtr->top;
    struct Node *topNode = sPtr->top;
    if (sPtr->size != 0)
    {
        sPtr->top = topNode->next;
        sPtr->size--;
        return returnNode->data;
    }
    else
    {
        fprintf(stderr, "Error: Stack is Empty!\n");
        return -1;
    }
}

unluddite answer中指出的另一个问题是你没有正确地推送数据。你需要两个修复才能安全。可能还有其他问题(例如没有正确释放内存 - 或根本没有),但这两个问题会让你走得很远。

相关问题