Hi everybody. I have trouble dynamically growing a stack.
Any help will be appreciated.
So, I have...
1 2 3 4 5 6 7 8 9 10
|
#define CAPACITY 128
typedef double ElemType;
typedef struct stack_struct *StackPtr;
typedef struct stack_struct StackStruct;
struct stack_struct{
ElemType items[CAPACITY];
int top;
};
|
than..., at a runtime a stack is being created dynamically.
1 2 3 4 5
|
StackPtr stk_create(){
StackPtr s = malloc(sizeof(struct stack_struct));
s->top = -1;
return s;
}
|
Now..., when the stack is full,I want to allocate a new chank of space and copy
the old stack in there. Problem is, I'm not shure how to do that.
If I do it the same way it is done in
stk_create
(use malloc and sizeof old stack
times 2), than won't it copy the whole struct with the array and
int top
in it?
Won't I have than a new struct with two
int top
s in it?
I was also thinking about just creating a new array two times the size of the
old one and than just point
s->items
to it, but than again, my professor told
me to make sure and
free()
every occurance of memory allocation done with malloc.
But I used malloc to allocate memory for the whole struct(with array and int in it).
What would I be freeing than if I will only resize the array
inside the struct?
Thank you.