What is the best correct way of implementing a dynamically resizing stack in C?
For example, i want to allocate an amount of memory to a stack but when that stack gets full, the memory allocated is doubled to accomodate new data, etc.
I have a stack implemented at the minute using a simple array of void pointers, this way i can store pointers of all types so it's quite reusable. When i try to implement this using malloc()/realloc() i run into errors while doing pointer math due to void pointers not having a size assigned.
What is the best correct way to implement a dynamically resizable stack in C?
EDIT:
I was trying something like this code (error checking removed) but i now understand that i can not interact with void pointers like this. So i'm just having a think how to do something like this legally. This is a big learning exercise for me as i've never really been exposed to C.
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
static int index = 0;
void* CreateStack(void)
{
void *stack = malloc(INITIAL_STACK_SIZE);
return stack;
}
void* Pop(void *stack)
{
return stack + index--;
}
void Push(void *stack, void *value)
{
*(stack + index) = value;
}
void FreeStack(void *stack)
{
free(stack);
}