fork download
  1. #include <stdio.h>
  2.  
  3. #define MAX 100
  4.  
  5. int stack[MAX];
  6. int sp = 0;
  7.  
  8. /* push関数 */
  9. int push(int data) {
  10. printf("[push開始] sp = %d\n", sp);
  11.  
  12. if (sp >= MAX) {
  13. return -1; // スタック満杯
  14. }
  15.  
  16. stack[sp] = data;
  17. sp++;
  18.  
  19. return 0;
  20. }
  21.  
  22. /* pop関数 */
  23. int pop(int *data) {
  24. printf("[pop開始] sp = %d\n", sp);
  25.  
  26. if (sp <= 0) {
  27. return -1; // スタック空
  28. }
  29.  
  30. sp--;
  31. *data = stack[sp];
  32.  
  33. return 0;
  34. }
  35.  
  36. /* スタック内容表示関数 */
  37. void printStack() {
  38. int i;
  39.  
  40. printf("Stack = [ ");
  41. for (i = 0; i < sp; i++) {
  42. printf("%d ", stack[i]);
  43. }
  44. printf("]\n");
  45. }
  46.  
  47. int main() {
  48. int x;
  49.  
  50. push(10);
  51. push(20);
  52. push(30);
  53.  
  54. printStack();
  55.  
  56. pop(&x);
  57. printf("popした値 = %d\n", x);
  58.  
  59. printStack();
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
[push開始] sp = 0
[push開始] sp = 1
[push開始] sp = 2
Stack = [ 10 20 30 ]
[pop開始] sp = 3
popした値 = 30
Stack = [ 10 20 ]