C中基于数组的堆栈实现

array based implementation of stack in C

我指的是基于数组的堆栈实现的来源。 在页面的某处,它说,

Dynamically-sized stack: Now, we will add one more choice to how we'll implement our stack. We want to be able to decide the maximum size of the stack at run-time (not compile-time).

Thus, we cannot use a regular array, but must use a pointer to a dynamically-allocated array.

Now, will we need to keep track of any more information besides the contents and top?

Answer: Yes! We'll need to keep the size of this array, i.e., the maximum size of the stack. We'll see why this is necessary as we write the code.

在 运行-time 决定堆栈的最大大小是什么意思,因为 我们需要保持数组的大小,即最大大小?我们仍然需要存储堆栈最大大小的变量以动态分配内存,所以我不太确定这与拥有常规数组并声明其容量(最大大小)相比有何好处。

因为使用动态分配的数组,您可以选择扩展它(在需要时分配更大的数组)或最小化它(释放一些内存以减少 RAM 使用)。

您可能指的是 malloc, realloc and free。您想要做的是使用 malloc 分配一些内存并将其大小保存在另一个变量中。

当堆栈耗尽时(即其中的项目数量等于其大小)- 您需要调用 realloc 到 "expand" 数组,并更新堆栈的大小.