【发布时间】:2018-11-26 10:43:25
【问题描述】:
问题是printf() 在pop() 方法中显示奇怪的地址并且不再运行。打印结果如下。
push (10)
push (20)
push (30)
push (40)
40
-842150451
这是完整的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node* head = NULL;
void init(){
head = (node*)malloc(sizeof(node));
head->data = 0;
head->next = NULL;
}
void push(int data){
node* temp = (node*)malloc(sizeof(node));
if(temp == NULL){
printf("Out Of Memory");
}else{
head = (node*)malloc(sizeof(node));
temp->data = data;
temp->next = head;
head = temp;
printf("push (%d)\n", data);
}
}
void pop(){
node* temp;
if(head == NULL) return;
temp = head;
printf("%d\n", head->data);
head = head->next;
free(temp);
}
void main(){
push(10);
push(20);
push(30);
push(40);
pop();
pop();
pop();
pop();
}
而且这个 pop 方法不起作用。 第一次显示40。
然后打印 -842150451。 我不明白为什么我会收到这个奇怪的号码。
void pop(){
node* temp;
if(head == NULL) return;
temp = head;
printf("%d\n", head->data);
head = head->next;
free(temp);
}
【问题讨论】:
标签: c data-structures linked-list stack