首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

尝试在C中通过结构实现堆栈,但得到以下代码的运行时错误。谁能解释并指出哪里出了问题?

在C语言中,通过结构实现堆栈的代码如下:

代码语言:txt
复制
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

void push(Stack *stack, int item) {
    if (stack->top == MAX_SIZE - 1) {
        printf("Stack Overflow\n");
        return;
    }
    stack->data[++stack->top] = item;
}

int pop(Stack *stack) {
    if (stack->top == -1) {
        printf("Stack Underflow\n");
        return -1;
    }
    return stack->data[stack->top--];
}

int main() {
    Stack stack;
    stack.top = -1;

    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);

    printf("%d\n", pop(&stack));
    printf("%d\n", pop(&stack));
    printf("%d\n", pop(&stack));
    printf("%d\n", pop(&stack));

    return 0;
}

这段代码实现了一个基本的堆栈数据结构。其中,结构体Stack包含一个整型数组data和一个整型变量top,用于存储堆栈元素和记录栈顶位置。push函数用于将元素入栈,pop函数用于将元素出栈。在main函数中,我们创建了一个堆栈对象stack,并进行了一些入栈和出栈操作。

然而,这段代码存在一个运行时错误。当我们尝试从空栈中进行出栈操作时,会导致数组越界访问,从而引发未定义的行为。具体来说,当栈为空时,pop函数会返回-1,但在main函数中,我们没有对返回值进行判断,直接打印出来。因此,当尝试从空栈中进行出栈操作时,会打印出-1,而不是提示栈下溢(Stack Underflow)的错误信息。

为了解决这个问题,我们可以在pop函数中增加一个标志位来表示栈是否为空,然后在main函数中根据该标志位来判断是否打印出栈下溢的错误信息。修改后的代码如下:

代码语言:txt
复制
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

void push(Stack *stack, int item) {
    if (stack->top == MAX_SIZE - 1) {
        printf("Stack Overflow\n");
        return;
    }
    stack->data[++stack->top] = item;
}

int pop(Stack *stack, int *isEmpty) {
    if (stack->top == -1) {
        *isEmpty = 1;
        return -1;
    }
    *isEmpty = 0;
    return stack->data[stack->top--];
}

int main() {
    Stack stack;
    stack.top = -1;

    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);

    int isEmpty;
    printf("%d\n", pop(&stack, &isEmpty));
    if (isEmpty) {
        printf("Stack Underflow\n");
    }
    printf("%d\n", pop(&stack, &isEmpty));
    if (isEmpty) {
        printf("Stack Underflow\n");
    }
    printf("%d\n", pop(&stack, &isEmpty));
    if (isEmpty) {
        printf("Stack Underflow\n");
    }
    printf("%d\n", pop(&stack, &isEmpty));
    if (isEmpty) {
        printf("Stack Underflow\n");
    }

    return 0;
}

在修改后的代码中,我们在pop函数的参数中增加了一个指向整型变量isEmpty的指针。当栈为空时,将isEmpty设置为1,否则设置为0。在main函数中,我们通过判断isEmpty的值来决定是否打印出栈下溢的错误信息。

这样修改后的代码可以正确处理栈下溢的情况,避免了运行时错误。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券