如何修改程序,以便在缺少分配的内存堆栈的情况下,在 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 (将#修改为@)