【问题标题】:Allocating 2 times more memory to my stack (only if needed) C为我的堆栈分配 2 倍的内存(仅在需要时)C
【发布时间】: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


【解决方案1】:

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

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;
}

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 2017-01-04
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2011-05-28
    • 2021-04-08
    • 2021-08-20
    相关资源
    最近更新 更多