gpt4 book ai didi

c - C语言中栈的push方法的实现

转载 作者:行者123 更新时间:2023-12-02 06:27:58 25 4
gpt4 key购买 nike

开发者!我有一个关于 C 中堆栈的 push() 方法的问题!

我在 C 中实现了自己的 push() 方法!但我无法理解结果!

下面是我的堆栈代码

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

#define MAX_SIZE 10

int top = -1;
int array[MAX_SIZE];

void init(){
top = -1;
}

void push(int array[], int data){

if(top > MAX_SIZE-1)
fprintf(stderr, "invalid top %d\n", top+1);
else{
array[++top] = data; // top == 9, ++top == 10
printf("top: %d data: %d\n", top+1, array[top]); // top == 11, top == 10
}
}
void pop(int array[]){

}
void peek(int array[]){

}

int main() {
int data = 1;

for (int i=0; i<MAX_SIZE; i++)
push(array, data++);
push(array, 100);
push(array, 200); // invalid top
push(array, 300); // invalid top
return 0;
}

这段代码的结果如下

top: 1 data: 1
top: 2 data: 2
top: 3 data: 3
top: 4 data: 4
top: 5 data: 5
top: 6 data: 6
top: 7 data: 7
top: 8 data: 8
top: 9 data: 9
top: 10 data: 10
top: 11 data: 100
invalid top 11
invalid top 11

我不明白的是..在结果中,当 top: 11 时,实际上就像 top: top+1。如果您查看我的 push() 方法中的 else 语句,您会注意到它。

但是,在 else 语句中,什么时候

printf("top: %d data: %d\n", 11, array[10]);
the result: top: 11 data: 100

,我觉得应该是报错了。因为我将数组大小声明为 10,即 MAX_SIZE。所以索引大小将为 0 ~ 9。但是 array[10] 是怎么工作的??

我真的不明白。

最佳答案

你可以这样做,因为 C 允许你这样做。但是你不应该因为在未分配的内存区域中写入是危险的。您的数组已分配 10 个整数长度。分配内存的 10 个整数。您尝试访问的第 11 个整数没有为其分配内存。

如评论中所述,如果您希望代码抛出错误,您需要的功能是绑定(bind)检查。这正是您在 push 函数的第一部分所做的。

将条件更改为 top >= MAX_SIZE - 1 以解决问题。

至于实现堆栈的更好方法,您可以尝试在链表之上实现一个,这样您就可以在不连续的内存区域中管理您的堆栈。

您还可以将 unsigned int 用于数组索引,因为您在那里不需要负数。

关于c - C语言中栈的push方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com