Guest User

Untitled

a guest
Nov 17th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #ifndef STACK_H
  2. #define STACK_H
  3.  
  4. #include <stdlib.h>
  5. #include <stddef.h>
  6.  
  7. #define DYNAMIC_ARRAY_INIT_CAPACITY 4
  8. #define DYNAMIC_ARRAY_GROWTH_FACTOR 2
  9.  
  10. typedef struct Stack
  11. {
  12. int size;
  13. int elementSize;
  14. int capacity;
  15. void *data;
  16. } Stack;
  17.  
  18. //Creates a stack
  19. inline Stack *StackCreate(int elementSize)
  20. {
  21. Stack *stack = malloc(sizeof(Stack));
  22. stack->size = 0;
  23. stack->elementSize = elementSize;
  24. stack->capacity = DYNAMIC_ARRAY_INIT_CAPACITY;
  25. stack->data = malloc(elementSize * stack->capacity);
  26. return stack;
  27. }
  28.  
  29. //Get an element from stack of index
  30. inline void *StackGet(Stack *stack, int index)
  31. {
  32. if (index < stack->size)
  33. return (char*)stack->data + (index * stack->elementSize);
  34. else
  35. return NULL;
  36. }
  37.  
  38. //Push an element to a stack
  39. inline void StackPush(Stack *stack, void *data)
  40. {
  41. if (stack->size >= stack->capacity)
  42. {
  43. //Allocate/set new data
  44. stack->capacity *= DYNAMIC_ARRAY_GROWTH_FACTOR;
  45. void *newLocation = malloc(stack->elementSize * stack->capacity);
  46. memcpy(newLocation, stack->data, stack->elementSize * stack->size);
  47.  
  48. //Free old data
  49. free(stack->data);
  50.  
  51. //Set new pointer
  52. stack->data = newLocation;
  53. }
  54.  
  55. //Add to size, and copy element data
  56. stack->size++;
  57. memcpy(StackGet(stack, stack->size - 1), data, stack->elementSize);
  58. }
  59.  
  60. //Pop an element from a stack
  61. inline void StackPop(Stack *stack)
  62. {
  63. stack->size--;
  64. }
  65.  
  66. //Free all memory of stack
  67. inline void StackFree(Stack **stack)
  68. {
  69. free((*stack)->data);
  70. free(*stack);
  71. *stack = NULL;
  72. }
  73.  
  74. #endif //STACK_H
Add Comment
Please, Sign In to add comment