language: C (gcc-4.7.2)
date: 190 days 6 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#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;
}