fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Stack {
  5. int capacity;
  6. int index;
  7. int *data;
  8. };
  9.  
  10. struct Stack * CreateStacks(int numberOfStacks)
  11. {
  12. // Should always check return from malloc for NULL...
  13. struct Stack *stack = malloc(numberOfStacks * sizeof(struct Stack));
  14. for (int i = 0; i < numberOfStacks; i++) {
  15. stack[i].capacity = 10;
  16. stack[i].index = 0;
  17. stack[i].data = malloc(10 * sizeof(int));
  18. }
  19. return stack;
  20. }
  21.  
  22. void FreeStacks(struct Stack *stack, int numberOfStacks)
  23. {
  24. for (int i = 0; i < numberOfStacks; i++) {
  25. free(stack[i].data);
  26. }
  27. free(stack);
  28. }
  29.  
  30. void Push(struct Stack *stack, int value) {
  31. // Check for reallocation
  32. if (stack->index == stack->capacity) {
  33. stack->capacity *= 2; //Assumes capacity >= 1
  34. stack->data = realloc(stack->data, sizeof(int) * stack->capacity);
  35. }
  36. // Set the data
  37. stack->data[stack->index++] = value;
  38. }
  39.  
  40. int Pop(struct Stack *stack)
  41. {
  42. if (stack->index < 0) return 0; // Error
  43. return stack->data[--stack->index];
  44. }
  45.  
  46. int main(void) {
  47. struct Stack *pml = CreateStacks(100);
  48. // Assign some values to first stack
  49. for (int i = 0; i < 25; i++) {
  50. Push(&pml[0], i);
  51. }
  52. // Print values
  53. for (int i = 0; i < 25; i++) {
  54. printf("%d ", Pop(&pml[0]));
  55. }
  56.  
  57. FreeStacks(pml, 100);
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0