使用堆栈在C中引发异常

使用堆栈在C中引发异常,c,C,我在研究数据结构。现在我试着用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 = mallo

我在研究数据结构。现在我试着用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;
}

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

stack_t structure = { arr, size, 0, 1};
element = pop(&structure);
因为堆栈在程序启动时是空的

第二,push函数按错误的顺序执行操作。一定是

void push(stack_t* s, uint8_t element)
{
    s->stack[s->top] = element;
    s->top = s->top + 1;
}
...
else
    {
        s->top = s->top - 1;
        return (s->stack[s->top]);
    }
因为我们想在0号位置开始推

第三,pop函数也会按错误的顺序进行操作。一定是

void push(stack_t* s, uint8_t element)
{
    s->stack[s->top] = element;
    s->top = s->top + 1;
}
...
else
    {
        s->top = s->top - 1;
        return (s->stack[s->top]);
    }
因为push函数在推送元素之后增加堆栈ptr,当我们想要拉取元素时,我们必须先减少堆栈指针,然后在这个位置获取元素

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

stack_t structure = { arr, size, 0, 1};
element = pop(&structure);
第五,打印元素的for循环具有错误的边界检查。使用:

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

对于这些问题,如果不推送超过10个元素,它应该可以工作,因为上限的健全性检查也丢失了。

这是非常错误的:
(uint32_t)malloc(…)
编译器应该在为指针分配整数类型时给您一个强烈的警告/错误。不要忽视这些警告。在这里发布之前修复它们。在这种情况下,正确的强制转换应该是
(uint32\u t*)
,但您应该完全取消强制转换,这是不需要的。但是通过将指针强制转换为整数,如果指针大于32位,则会被强制转换破坏。
if(stack\u empty(&s))
应该是
if(stack\u empty(s))
s
已经是一个指针,所以您要传递的是它的值,而不是它的地址。字段
元素
下溢
溢出
不应该是堆栈结构的一部分。@Gerhardh很抱歉that@DimaRich是的,谢谢,我自己也考虑过不客气。我可能会用几次“错”和“一定是”来粗声说话。不是故意的。当然,做事总有几种方法。