erikenz
erikenz

Reputation: 3

Allocating 2 times more memory to my stack (only if needed) C

I have a code in C language with a stack that has defined size of 3 and i need the program to be able to allocate 2x more size if its needed. The code now looks like this :

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

If somebody can help.

Upvotes: 0

Views: 73

Answers (1)

Paul Yang
Paul Yang

Reputation: 346

I'm not very sure is this what you want?

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

Upvotes: 1

Related Questions