使用C的简单堆栈实现

时间:2011-07-17 06:14:25

标签: c

我用C编写了一个程序来实现一个简单的堆栈。但我在程序中遇到分段错误,发现很难找出错误。任何人都可以提供帮助,

   #include<stdio.h>
   #include<stdlib.h>
   struct stack_structure{
     int stack_array[10];
     int stack_pointer;
   };
   void push_into_stack(struct stack_structure *,int);
   int main(){
     int no = 8;
     struct stack_structure *st;
     st->stack_pointer = -1;
     push_into_stack(st,no);
     return 0;
   }
   void push_into_stack(struct stack_structure *s,int no){
     s -> stack_pointer++;
     s -> stack_array[s -> stack_pointer] = no;
   }

3 个答案:

答案 0 :(得分:6)

struct stack_structure *st;

这只会创建一个指向struct stack_structure的指针。它不为struct stack_structure本身分配内存。

你可以试试这个:

struct stack_structure st;
st.stack_pointer = -1;
push_into_stack(&st,no);

另一种选择是动态分配(和释放)该结构:

struct stack_structure *st = malloc(sizeof(struct stack_structure));
...
// when you're done with it
free(st);

答案 1 :(得分:4)

参见以下几行:

 struct stack_structure *st;
 st->stack_pointer = -1;

你已经声明了一个指针变量但是你没有初始化它。指针必须指向某个东西,而这个指针没有任何指向。最简单的解决方法是将这些行更改为:

 struct stack_structure st1, *st=&st1;
 st->stack_pointer = -1;

答案 2 :(得分:0)

你需要为结构malloc一些空间:

struct stack_structure *st = malloc(sizeof(struct stack_structure));