c - 结构程序停止,没有任何错误

标签 c pointers data-structures stack

这是一个使用结构指针实现堆栈的简单程序。但是,在运行代码时,我的程序退出时没有显示任何错误。

#include<stdio.h>
#include<stdlib.h>

#define maxsize 5

struct s
{
    char array[maxsize];
    int top;
};
typedef struct s stack;


int insert(stack *p)
{
    char ch;
    /*if(p->top==NULL)
      {
      p->top=-1;
      }*/
    if(p->top>=maxsize-1)
    {
        printf("Stack overflows on insertion\n");
    }
    else
    {
        printf("Enter the character to be inserted : ");
        scanf("\n%c",&ch);
        p->top++;
        p->array[p->top]=ch;
    }
}
int delete(stack *p)
{
    if(p->top==-1)
    {
        printf("Stack underflows on deletion\n");
    }
    else
    {
        p->top--;
    }
}
int display(stack *p)
{
    int i;
    if(p->top==-1)
    {
        printf("Stack is empty\n");
    }
    else
    {
        for(i=0;i<=p->top;i++)
        {
            printf("%c",p->array[i]);
        }
        printf("\n");
    }
}

int main()
{
    int c;
    stack *p;
    p->top=-1;
    while(1)
    {
        printf("1--> INSERT  2--> DELETE  3--> DISPLAY\n");
        scanf("%d",&c);
        switch(c)
        {
            case 1:
                insert(p);
                break;
            case 2:
                delete(p);
                break;
            case 3:
                display(p);
                break;
            default:
                printf("ERROR : Invalid Choice");
        }
    }
}

该程序包含三个函数,用于压入、弹出和显示堆栈中的元素,最后一个主函数是执行函数调用的地方。

程序编译成功,错误为 0,但在运行时退出,不显示任何内容。

最佳答案

当您声明时:

  stack *p;

它只是声明一个指针。如果您想使用指针,则需要分配内存 - 正如您在此处所做的那样(这将出现段错误):

   p->top=-1;

将第一行更新为以下内容:

   stack *p = malloc(sizeof(stack));

malloc() 将分配所请求的内存以供使用 - 任何动态分配的内存也应该是 free() 的

关于c - 结构程序停止,没有任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58069345/

相关文章:

C 中的 union 解引用和递减

python - 实现一个带约束的 python 列表

algorithm - 堆上的摊销分析

algorithm - 排序间隔查询

c - massif 的内存计数和 memcheck 的内存计数有什么区别?

c++ - char * 是什么意思

c++ - 如何使用 std::sort() 对指向值的 vector 进行排序?

c++ - 将__attribute __((const))放在可以访问全局内存的函数上也完全取决于输入的函数是否正确/值得?

使用宏检查 C 中的类型大小

java - Java中linkedList实现的删除方法