Rui Moreira
Rui Moreira

Reputation: 167

Change array size inside a struct

I'm trying to simulate a stack (pushing and poping values into the top of the stack) using structs and dynamic memory allocation in C and I have this struct:

...
#define max 5

typedef struct stack  
{
    int stk[max];
    int top;
}STACK;
...

I successfully simulated the stack, but when it reaches its maximum size (stack is full) I want to change the value of max in order to keep adding (push) values to the top of the stack. In other words, i just want to reallocate the max value in the stk field of the struct, if that is possible.

Any suggestion is appreciated.

Upvotes: 2

Views: 4196

Answers (3)

Michele d'Amico
Michele d'Amico

Reputation: 23711

As @user694733 as pointed out you must use dynamic memory. An other example can be:

typedef struct stack  
{
    int top;
    int max;
    int stk[];
}STACK;

STACK *init_stack(int m){
    STACK *st = (STACK *)malloc(sizeof(STACK)+m*sizeof(int));
    st->top = 0;
    st->max = m;
    return st;
}

STACK *resize_stack(STACK *st, int m){
    if (m<=st->max){
         return st; /* Take sure do not kill old values */
    }
    STACK *st = (STACK *)realloc(sizeof(STACK)+m*sizeof(int));
    st->max = m;
    return st;
}

Now you can use that function in your program like:

void main(void){
    STACK *st = init_stack(5);
    .... do something bu you need more room....
    st = resize_stack(st,100);
    ..... Now is small again .....
    st = resize_stack(st,5);
} 

Take care that every realloc call have a linear cost and so you cannot use it to add just a constant number of elements: better use a geometric expansion. Take a look to http://en.wikipedia.org/wiki/Dynamic_array as a start point for dynamic array.

Upvotes: 1

Gophyr
Gophyr

Reputation: 406

Try it like this:

typedef struct stack
{
  int *stk;
  int top;
}

signed int array_resize(stack *s, size_t size)
{
  if(!s) return -1;

  s->stk = realloc(s->stk, size * sizeof(int));

  return 0;
}

This reallocates the space for the array of integers. I don't know how else to make this work.

Upvotes: 0

user694733
user694733

Reputation: 16043

Using int stk[max]; is not dynamic memory allocation.

You need to have pointer int * stk; and initialize it with malloc. Then realloc when more memory is needed. And when stack is no longer needed, release it with free.

Upvotes: 4

Related Questions