【发布时间】:2015-09-29 15:33:00
【问题描述】:
#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 函数时,无论我调用多少次函数,它都会显示不同的内存地址。在代码中找不到问题。请帮忙。
【问题讨论】:
-
除了
free在push中的错误(如答案中已经提到的),don't cast the result of malloc。