繁体   English   中英

在带有堆栈的 C 中引发异常

[英]Exception thrown in C with stack

我正在研究数据结构。 现在我尝试用语言 C 编写一些堆栈,不幸的是没有成功。

在 switch 语句中的情况 4 中,我有这样的错误:抛出异常:读取访问冲突。

可能有什么错误?

这是我的代码:

int main(int argc, char** argv)
{
    int size;
    int element;

    printf("enter the size of stack: ");
    scanf("%d", &size);

    uint32_t* arr = malloc(sizeof(uint32_t) * size);
    stack_t structure= { arr, size, 0};

    int check = 1;

    while (check == 1)
    {
        int op;
        int condition;

        printf("Enter the action: 1) check stack for empty; 2) push function; 3) pop function; 4) print stack\n");
        printf("Command: ");
        scanf("%d", &op);
        printf("\n");

        switch (op)
        {
        case 1:
            structure.empty = stack_empty(&structure);
            break;

        case 2:
            printf("enter the number to be pushed: ");
            scanf("%d", &element);
            push(&structure, element);
            break;

        case 3:
            structure.stack = pop(&structure);
            break;

        case 4:
            for (int i = 0; i < structure.size; i++)
                printf("[%d] = %d\n", i, structure.stack[i]);


            break;
        default:
            printf("The command is not found, try again\n");
            break;
        }

        printf("Continue? y/n(1/0)\n");
        scanf("%d", &condition);

        check = condition;
    }

    system("pause");
    return 0;
}

这是可能无法正常工作的功能

typedef struct stack
{
    uint32_t* stack;
    int size;
    uint8_t top;
    uint8_t empty;
}stack_t;


int stack_empty(stack_t* s)
{
    if (s->top == 0)
        return 1;
    else
        return 0;
}

void push(stack_t* s, uint8_t element)
{
    s->top = s->top + 1;
    s->stack[s->top] = element;
}


int pop(stack_t* s)
{
    if (stack_empty(s))
    {
        printf("stack is underflow\n");
        exit(1);
    }
    else
    {
        s->top = s->top - 1;
        return (s->stack[s->top + 1]);
    }
}

首先,结构初始化不正确。 肯定是

stack_t structure = { arr, size, 0, 1};

因为堆栈在程序启动时是空的。

其次,push function 做错了事情。 肯定是

void push(stack_t* s, uint8_t element)
{
    s->stack[s->top] = element;
    s->top = s->top + 1;
}

因为我们想从 pos 0 开始推。

第三,pop function 的顺序也有误。 肯定是

...
else
    {
        s->top = s->top - 1;
        return (s->stack[s->top]);
    }

因为 push function 在 push 元素后增加了堆栈 ptr,当我们想要拉一个元素时,我们必须先减少堆栈指针,然后在这个 position 处获取元素。

第四,案例3是错误的。 肯定是

element = pop(&structure);

第五,打印元素的 for 循环有错误的边界检查。 利用:

for (int i = 0; i < structure.top; i++)
                printf("[%d] = %d\n", i, structure.stack[i]);

关于这些问题,如果不推送超过 10 个元素,它应该可以工作,因为也缺少对上限的完整性检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM