堆栈在 c 中弹出时显示内存地址

stack showing memory address on pop in c

#include <stdio.h>
#include <stdlib.h>

typedef struct x {
    int data;
    struct x *next;
} stack;

int main(){
    stack *head;
    int choice, num;
    head = NULL;

    /* function prototypes */
    void push(stack **head, int item);
    int pop(stack **head);
    int peek(stack *head);

    /* program */
    do{
        printf("\n1. Push Element\n2. Pop Element\n3. Peek The First Element\n4. Exit");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch(choice){
            case 1:
                printf("\n\nEnter the number to be pushed: ");
                scanf("%d", &num);
                push(&head, num);
                break;
            case 2:
                printf("%d\n", pop(&head));
                break;
            case 3:
                printf("%d is the top element\n", peek(head));
                break;
            default:
                system("cls");
                break;
        }
    }while(choice!=4);
}

void push(stack **head, int item){
    stack *ptr;
    ptr = (stack *)malloc(sizeof(stack));
    ptr->data = item;
    ptr->next = *head;
    *head = ptr;
    free(ptr);
}

int pop(stack **head){
    if(*head == NULL) return -1;
    int item = (*head)->data;
    *head = (*head)->next;
    return item;
}

int peek(stack *head){
    if(head == NULL) return -1;
    return head->data;
}

代码中有什么问题? 每当我弹出或查看内存地址而不是推送的值时。当调用 peek 时,会显示一个内存地址,当调用 pop 函数时会弹出该地址,此后每当调用 pop 函数时,无论我调用该函数多少次,它都会显示不同的内存地址。找不到代码中的问题。请帮忙。

您正在释放要显示的指针。在 push 中,当你 free(ptr) 时,head 指向 ptr。所以,基本上你是在释放头脑。这意味着没有任何东西会被压入堆栈。你应该做的是释放 pop 上的数据,并实现一个函数来遍历堆栈并在退出时释放堆栈中剩余的所有内容。