简体   繁体   English

C中基于数组的堆栈实现

[英]array based implementation of stack in C

I'm referring to this source for array-based implementation of stacks. 我指的是基于堆栈的基于数组的实现的源。 Somewhere on the page, it says, 它在页面的某处说:

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, ie, the maximum size of the stack. 我们需要保持该数组的大小,即堆栈的最大大小。 We'll see why this is necessary as we write the code. 我们将在编写代码时看到为什么这样做是必要的。

What does it mean to decide the maximum size of the stack at run-time , given the fact that we need to keep the size of the array, ie max size ? 考虑到我们需要保持数组大小(即最大大小)的事实, 决定运行时堆栈的最大大小是什么意思? we still need the variable that stores the max size of the stack for dynamically allocating memory so I'm not quite sure how this would be beneficial as opposed to having a regular array and declaring capacity(max size) of it. 我们仍然需要用于存储堆栈最大大小的变量以动态分配内存,因此我不太确定这与使用常规数组并声明其容量(最大大小)相比会有什么好处。

Because using a dynamically allocated array, you may choose to expand it (allocate a larger array when needed) or to minimize it (free some memory to reduce RAM usage). 因为使用动态分配的数组,所以您可以选择扩展它(在需要时分配更大的数组)或最小化它(释放一些内存以减少RAM使用)。

What you'd be probably referring to is malloc , realloc and free . 您可能要指的是mallocreallocfree What you'd want to do is to allocate some memory using malloc and keep its size in another variable. 您要做的是使用malloc分配一些内存,并将其大小保留在另一个变量中。

When the stack is exhausted (ie the amount of items in it is equal to its size) - you'd want to call realloc to "expand" the array, and update the stack's size. 当堆栈耗尽时(即其中的项目数量等于其大小),您需要调用realloc来“扩展”数组,并更新堆栈的大小。

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

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