【发布时间】:2021-05-24 05:14:15
【问题描述】:
我有一个 C 语言代码,其堆栈的定义大小为 3,如果需要,我需要程序能够分配 2 倍的大小。代码现在看起来像这样:
#include <stdio.h>
#include <stdlib.h>
struct stack {
char *items;
int max;
int count;
};
struct stack *
stack_init(int max)
{
struct stack *s = (struct stack *) malloc(sizeof(struct stack));
s->items = (char *) malloc(sizeof(char) * max);
s->max = max;
s->count = 0;
return s;
}
void
stack_destroy(struct stack *s)
{
free(s->items);
free(s);
}
int
stack_isempty(struct stack *s)
{
return 0 == s->count;
}
int
stack_push(struct stack *s, char item)
{
if (s->count >= s->max)
return -1;
s->items[s->count] = item;
++(s->count);
return 0;
}
int
stack_pop(struct stack *s, char *item)
{
if (s->count <= 0)
return -1;
--(s->count);
*item = s->items[s->count];
return 0;
}
void
main(void)
{
struct stack *s = stack_init(3);
printf("free? %d\n\n", stack_isempty(s));
printf("Error pushu? %d\n", stack_push(s, 'A'));
printf("free? %d\n\n", stack_isempty(s));
printf("error pushu? %d\n", stack_push(s, 'B'));
printf("free? %d\n\n", stack_isempty(s));
printf("error pushu? %d\n", stack_push(s, 'C'));
printf("free? %d\n\n", stack_isempty(s));
char ch;
printf("error popu? %d\n", stack_pop(s, &ch));
printf("Pop returned (if returned): %c\n", ch);
printf("free? %d\n\n", stack_isempty(s));
printf("error popu? %d\n", stack_pop(s, &ch));
printf("Pop returned (if returned): %c\n", ch);
printf("free? %d\n\n", stack_isempty(s));
printf("error popu? %d\n", stack_pop(s, &ch));
printf("Pop returned (if returned): %c\n", ch);
printf("free? %d\n\n", stack_isempty(s));
stack_destroy(s);
}
如果有人可以提供帮助。
【问题讨论】:
-
现在您需要对其进行格式化以使其对人类可读。
-
您在寻找realloc 函数吗?因为不清楚你的具体问题是什么。你已经描述了你想做什么,但没有提出问题或解释什么具体问题阻碍了你的进步。
-
在你的推送函数中,你检查堆栈是否已满...如果是,只需重新分配而不是返回错误代码(如果失败,你仍然可以这样做)。
标签: c memory-management stack