fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct Stack
  5. {
  6. int top, length, sizeofeach;
  7. void* start_ptr[];
  8. } Stack;
  9.  
  10. Stack* init_stack(int n_items, int sizeofeach)
  11. {
  12. Stack* stack;
  13. stack = malloc(sizeof(int) * 3 + sizeof(void*) * n_items);
  14.  
  15. stack->top = -1;
  16. stack->length = n_items;
  17. stack->sizeofeach = sizeofeach;
  18.  
  19. return stack;
  20. }
  21.  
  22. Stack* increase_stacksize(Stack* stack, int n_itemsToAdd)
  23. {
  24. Stack* newstack;
  25. newstack = realloc(stack, sizeof(*stack) + sizeof(void*) * (n_itemsToAdd + stack->length));
  26.  
  27. if(newstack != NULL)
  28. //printf("\nDebug print - array reallocated\n");
  29.  
  30. free(stack);
  31. stack = newstack;
  32.  
  33. stack->length += n_itemsToAdd;
  34.  
  35. return stack;
  36. }
  37.  
  38. Stack* push(Stack* stack, void* item)
  39. {
  40. if(stack->top + 1 == stack->length){
  41.  
  42. stack = increase_stacksize(stack, 10);
  43. }
  44.  
  45. int pos = stack->top + 1;
  46.  
  47. stack->start_ptr[pos] = item;
  48. ++(stack->top);
  49.  
  50. return stack;
  51. }
  52.  
  53. void printstack(Stack* stack)
  54. {
  55. printf("Number of items in the stack = %d\n", stack->top + 1);
  56. printf("Capacity of the stack = %d\n", stack->length);
  57.  
  58. printf("Elements in the stack are: \n");
  59.  
  60. int i;
  61.  
  62. for(i = 0; i <= stack->top; i++){
  63. int* item_ptr;
  64. void* address;
  65.  
  66. address = stack->start_ptr[i];
  67.  
  68. item_ptr = (int*)address;
  69.  
  70. printf("Position = %d, Item = %d \n", i, *item_ptr);
  71. }
  72. }
  73.  
  74. int main(void)
  75. {
  76. Stack* stack;
  77. stack = init_stack(5, sizeof(int));
  78.  
  79. int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  80. int i;
  81.  
  82. for(i = 0; i < 10; i++)
  83. {
  84. stack = push(stack, (void*)(a+i));
  85. }
  86.  
  87. printstack(stack);
  88.  
  89. //free(stack);
  90.  
  91. return 1;
  92. }
Runtime error #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
Number of items in the stack = 10
Capacity of the stack = 15
Elements in the stack are: 
Position = 0, Item = 1 
Position = 1, Item = 2 
Position = 2, Item = 3 
Position = 3, Item = 4 
Position = 4, Item = 5 
Position = 5, Item = 6 
Position = 6, Item = 7 
Position = 7, Item = 8 
Position = 8, Item = 9 
Position = 9, Item = 10