如何解决如何修改程序,以便在缺少分配的内存堆栈的情况下,在 C 中重新分配双倍大小的内存?
如何修改程序,以便在缺少分配的内存堆栈的情况下在 C 中重新分配双倍大小的内存?
这是我目前编写的代码。
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()
{
struct stack *s = stack_init(3);
printf("Is it empty? %d\n\n",stack_isempty(s));
printf("Push error? %d\n",stack_push(s,'A'));
printf("Is it empty? %d\n\n",'B'));
printf("Is it empty? %d\n\n",'C'));
printf("Is it empty? %d\n\n",stack_isempty(s));
char ch;
printf("Pop error? %d\n",stack_pop(s,&ch));
printf("Pop returned: %c\n",ch);
printf("Is it empty? %d\n\n",stack_isempty(s));
printf("Pop error? %d\n",stack_isempty(s));
printf("Pop erorr? %d\n",stack_isempty(s));
stack_destroy(s);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。