微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为我的堆栈分配 2 倍的内存仅在需要时C

如何解决为我的堆栈分配 2 倍的内存仅在需要时C

我有一个 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",'B'));
    printf("free? %d\n\n",'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_isempty(s));

    stack_destroy(s);
}

如果有人可以帮忙。

解决方法

我不太确定这是你想要的吗?

int
stack_push(struct stack *s,char item)
{
        int max = 0;

        if (s->count >= s->max){
                max = s->max * 2;
                s->items = (char*)realloc(s->items,sizeof(char)*max);
                if(NULL==s->items){
                        return -1;
                }
                s->max = max;
        }

        s->items[s->count] = item;
        ++(s->count);

        return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。