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

Posted

技术标签:

【中文标题】为我的堆栈分配 2 倍的内存(仅在需要时)C【英文标题】:Allocating 2 times more memory to my stack (only if needed) 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 函数吗?因为不清楚你的具体问题是什么。你已经描述了你想做什么,但没有提出问题或解释什么具体问题阻碍了你的进步。 在你的推送函数中,你检查堆栈是否已满...如果是,只需重新分配而不是返回错误代码(如果失败,你仍然可以这样做)。 【参考方案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;

【讨论】:

以上是关于为我的堆栈分配 2 倍的内存(仅在需要时)C的主要内容,如果未能解决你的问题,请参考以下文章

gcc需要很多内存来编译堆栈上具有非常大的对象的c ++文件

在 Aleph One 上工作时,在 64 位系统上没有堆栈分配

我最好为我的进程保留内存吗?

为啥我们不能在堆栈上分配动态内存?

堆栈与堆栈和堆与堆

为什么我们不能在堆栈上分配动态内存?