开发者

A simple stack implementation using C

开发者 https://www.devze.com 2023-03-21 07:06 出处:网络
I had written a program in C to implement a simple stack. But I am getting segmentation fault in my program and finding it hard to find out what is wrong. Can any one help,

I had written a program in C to implement a simple stack. But I am getting segmentation fault in my program and finding it hard to find out what is wrong. Can any one help,

   #include<stdio.h>
   #include<stdlib.h>
   struct stack_structure{
     int stack_array[10];
     int stack_pointer;
 开发者_Go百科  };
   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;
   }


struct stack_structure *st;

This only creates a pointer to a struct stack_structure. It does not allocate memory for the struct stack_structure itself.

You can try with this:

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

The other option is to dynamically allocate (and free) that structure:

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


See these lines:

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

You've declared a pointer variable but then you're using it uninitialized. A pointer has to point at something, and this one doesn't have anything to point to. The simplest fix would be to change these lines to:

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


You need to malloc some space for the structure:

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

精彩评论

暂无评论...
验证码 换一张
取 消