#include <stdlib.h>
#include <stdio.h>

typedef struct Stack
{
    int top, length, sizeofeach;
    void* start_ptr[];
} Stack;

Stack* init_stack(int n_items, int sizeofeach)
{
    Stack* stack;
    stack = malloc(sizeof(int) * 3 + sizeof(void*) * n_items);

    stack->top = -1;
    stack->length = n_items;
    stack->sizeofeach = sizeofeach;

    return stack;
}

Stack* increase_stacksize(Stack* stack, int n_itemsToAdd)
{
    Stack* newstack;    
    newstack = realloc(stack, sizeof(*stack) + sizeof(void*) * (n_itemsToAdd + stack->length));
    
    if(newstack != NULL)
        //printf("\nDebug print - array reallocated\n");

    free(stack);
    stack = newstack;

    stack->length += n_itemsToAdd;

    return stack;
}

Stack* push(Stack* stack, void* item)
{
    if(stack->top + 1 == stack->length){
        
        stack = increase_stacksize(stack, 10);
    }

    int pos = stack->top + 1;

    stack->start_ptr[pos] = item;
    ++(stack->top);
    
    return stack;
}

void printstack(Stack* stack)
{
    printf("Number of items in the stack = %d\n", stack->top + 1);
    printf("Capacity of the stack = %d\n", stack->length);

    printf("Elements in the stack are: \n");

    int i;

    for(i = 0; i <= stack->top; i++){
        int* item_ptr;
        void* address;

        address = stack->start_ptr[i];

        item_ptr = (int*)address;

        printf("Position = %d, Item = %d \n", i, *item_ptr);
    }
}

int main(void)
{    
    Stack* stack;
    stack = init_stack(5, sizeof(int));

    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int i;
    
    for(i = 0; i < 10; i++)
    {
        stack = push(stack, (void*)(a+i));
    }

    printstack(stack);
    
    //free(stack);
    
    return 1;
}