使用指针实现堆栈

时间:2017-08-11 20:37:07

标签: c pointers data-structures structure

我正在尝试使用指针和结构实现Stacks推送和弹出操作。此代码在第40行(s->entry=(StackEntry *)malloc(sizeof(StackEntry)*(n+1));)给出了错误,说明了分段错误。请帮忙

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    typedef long int StackEntry ;
    typedef int Boolean;

typedef struct stack{
    int top;
    int size;
    StackEntry *entry; //pointer to dynamic array
}Stack;
Boolean StackEmpty(Stack *s)
{
    return s->top<=0;
}
Boolean StackFull(Stack *s)
{
    return s->top >= s->size;
}
void Error(char *msg)
{
    puts(msg);
}
int StackSize(Stack *s)
{
    return s->top ;
}
void StackTop(StackEntry *item,Stack *s)
{
    *item=s->entry[s->top];
}
void CreateStack(Stack *s,int n)
{
    s->top=0;
    s->size=n;
    s->entry=(StackEntry *)malloc(sizeof(StackEntry)*(n+1)); 
}
void Push(StackEntry item,Stack *s)
{
    if(StackFull(s))
        Error("Stack is full");
    else s->entry[s->top++]=item;
}
int main() {

    int n;
    scanf("%d",&n);
    Stack *s;
    CreateStack(s,n);
    Push(10,s);
    //Push(15,s);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

尝试更改main()函数,如下所示:

int main() {                            
    int n;            
    scanf("%d",&n);   
    Stack s;          
    CreateStack(&s,n);
    Push(10,&s);      
    //Push(15,s);     
    return 0;         
}

正如BLUEPIXY所指出的那样,Stack *sStack结构声明一个指针,当你想要的是一个新的结构本身时。如果你需要main()范围之外的结构,你也可以为它声明堆栈指针,然后是malloc内存。