fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int *stackbase;
  6. int *stack;
  7. int stack_size;
  8.  
  9. void stackerr(char* str)
  10. {
  11. printf("%s\n", str);
  12. exit(999);
  13. }
  14.  
  15. void init_stack(int smax)
  16. {
  17. stackbase = (int *)malloc(smax * sizeof(int));
  18. if (stackbase == NULL)
  19. {
  20. stackerr("init error");
  21. }
  22. stack = stackbase;
  23. stack_size = smax;
  24. }
  25.  
  26. void extend_stack(void)
  27. {
  28. int *p, new;
  29. new = stack_size * 2;
  30. p = (int *)realloc(stackbase, new * sizeof(int));
  31. if (p == NULL)
  32. {
  33. stackerr("extend error");
  34. }
  35. stack = p + (stack - stackbase);
  36. stackbase = p;
  37. stack_size = new;
  38. }
  39.  
  40. void print_stack(void)
  41. {
  42. int *p = stack;
  43. int n = 0;
  44. while (p > stackbase)
  45. {
  46. p--;
  47. printf("%d: %d\n", n, *p);
  48. n++;
  49. }
  50. }
  51.  
  52. void push(int x)
  53. {
  54. if (stack >= stackbase + stack_size)
  55. {
  56. extend_stack();
  57. }
  58. *stack = x;
  59. stack++;
  60. }
  61.  
  62. int pop(void)
  63. {
  64. if (stack <= stackbase)
  65. {
  66. stackerr("Underflow");
  67. }
  68. stack--;
  69. return *stack;
  70. }
  71.  
  72. void calc(int *a, int c)
  73. {
  74. int x;
  75. int y;
  76. int i;
  77. int n;
  78. for (i = 0; i < c; i++)
  79. {
  80. n = a[i];
  81. if (n == -10000)
  82. {
  83. y = pop();
  84. x = pop();
  85. push(x + y);
  86. }
  87. else if (n == -10001)
  88. {
  89. y = pop();
  90. x = pop();
  91. push(x * y);
  92. }
  93. else if (n == -10002)
  94. {
  95. printf("%d\n", pop());
  96. break;
  97. }
  98. else
  99. {
  100. push(n);
  101. }
  102. }
  103. }
  104.  
  105. int main(int argc, char* argv[])
  106. {
  107. int i;
  108. char* arg;
  109. int x;
  110. int y;
  111.  
  112. init_stack(1);
  113. for (i = 1; i < argc; i++)
  114. {
  115. arg = argv[i];
  116. if (strcmp(arg, "+") == 0)
  117. {
  118. y = pop();
  119. x = pop();
  120. push(x + y);
  121. }
  122. else if (strcmp(arg, "x") == 0)
  123. {
  124. y = pop();
  125. x = pop();
  126. push(x * y);
  127. }
  128. else if (strcmp(arg, "p") == 0)
  129. {
  130. printf("%d\n", pop());
  131. }
  132. else
  133. {
  134. push(atoi(arg));
  135. }
  136. }
  137.  
  138. return EXIT_SUCCESS;
  139. }
  140.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty