【发布时间】:2016-01-18 10:28:15
【问题描述】:
我正在编写这个程序,我想了解为什么我得到了错误的打印(应该是 1、2、3、4、5)给出了一些地址。我的stackIsEmpty() 甚至没有像它的意思那样在堆栈为空时停止打印值。这是我的代码:
#include <stdlib.h>
#include <stdio.h>
//Stacks using Structures and linked list and pointerws.
typedef struct Stack{
//Type of the elements of the stack. Here integers
int elem;
//To of the stack
struct Stack* previous;
} Stack;
void initialize(Stack *st);
void push(Stack *st, int element);
int pop(Stack *st);
int stackIsEmpty(Stack *st);
int main(){
int i;
Stack st;
Stack *pt_st = &st;
initialize(pt_st);
//Test phase...
for(i=0; i<5; i++)
push(pt_st, i+1);
for(i=0; i<5; i++)
printf("here is one element: %d\n", pop(pt_st));
//End of test with error!
return 0;
}
void initialize(Stack *st){
st = NULL;
}
void push(Stack *st, int element){
Stack *sta = (Stack*)malloc(sizeof(Stack));
if (sta != NULL)
{
sta->previous = st;
sta->elem = element;
st = sta;
free(sta);
}
else
exit(0);
}
int pop(Stack *st){
if(!stackIsEmpty(st))
{
printf("stack is empty cannot pop\n");
return 0;
}
else
{
int number = st->elem;
Stack* copy = st->previous;
free(st);
st = copy;
return number;
}
}
int stackIsEmpty(Stack *st){
if(st == NULL)
return 0;
else
return 1;
}
【问题讨论】:
-
st = sta; free(sta);??这是什么? -
我想我可以将
sta的地址放入st。我将分配的空间释放给变量sta。 -
您是否使用调试器单步执行了代码
标签: c pointers linked-list