###配列とアドレスやポインタを組み合わせたプログラムを作成中です
先日学校でアドレスやポインタを学び、その応用として配列をmain関数内のローカルのみで実現しようというプログラムを作成しています。
まだまだ作成途中なのですが、どうしてもわからなく先に進めていない状態です。
###該当のソースコード
C
1#include <stdio.h> 2#include <stdlib.h> 3#define true 1 4#define false !true 5#define STACKSIZE 10 6 7#define bool int //typedef int bool; 8 9bool push(int data, int *stack, int *top); 10int pop(int *stack, int *top); 11int peek(int *stack, int *top); 12bool is_full(int top); 13bool is_empty(int top); 14void print_stack(int *stack, int top); 15 16int main(void) 17{ 18 int stack[STACKSIZE]; 19 int top = 0; 20 int *p_top; 21 22 p_top = ⊤ 23 24 push(1000, stack, p_top); 25 printf("[0]=%d\n", stack[0]); 26 printf("{1}=%d\n", stack[1]); 27 printf("{2}=%d\n", stack[2]); 28 push(2000, stack, p_top); 29 printf("[0]=%d\n", stack[0]); 30 printf("{1}=%d\n", stack[1]); 31 printf("{2}=%d\n", stack[2]); 32 push(3000, stack, p_top); 33 printf("[0]=%d\n", stack[0]); 34 printf("{1}=%d\n", stack[1]); 35 printf("{2}=%d\n", stack[2]); 36 print_stack(stack, top); 37 38 pop(stack, p_top); 39 printf("[0]=%d\n", stack[0]); 40 printf("{1}=%d\n", stack[1]); 41 printf("{2}=%d\n", stack[2]); 42 print_stack(stack, top); 43 pop(stack, p_top); 44 printf("[0]=%d\n", stack[0]); 45 printf("{1}=%d\n", stack[1]); 46 printf("{2}=%d\n", stack[2]); 47 print_stack(stack, top); 48 pop(stack, p_top); 49 printf("[0]=%d\n", stack[0]); 50 printf("{1}=%d\n", stack[1]); 51 printf("{2}=%d\n", stack[2]); 52 print_stack(stack, top); 53 54 return 0; 55} 56 57 58bool push(int data, int *stack, int *top) { 59 60 if (is_full(*top) ){ 61 return false; 62 } 63 else { 64 65 //*(stack + *top++) = data; 66 //*(stack + *(top++)) = data; 67 //*(stack + (i++)) = data; 68 /* *(stack+(*top)) = data; 69 *top = *(top + 1);*///動作停止 70 *(stack + *top) = data; 71 *top++; 72 return true; 73 74 } 75} 76 77int pop(int *stack, int *top) { 78 if (is_empty(*top)) { 79 fprintf(stderr, "Error:stack is empty.\n"); 80 return EXIT_FAILURE; 81 } 82 else { 83 return *(stack + *top--); 84 } 85} 86 87int peek(int *stack, int *top) { 88 if (is_empty(*top)) { 89 fprintf(stderr, "Error: stack is empty.\n"); 90 return EXIT_FAILURE; 91 } 92 else { 93 return *(stack + *top - 1); 94 } 95} 96 97bool is_full(int top) { 98 return top == STACKSIZE; 99} 100 101bool is_empty(int top) { 102 return top == 0; 103} 104 105void print_stack(int *stack, int top) { 106 int i = top - 1; 107 puts(""); 108 while (i >= 0) { 109 printf("%d| %d\n", i, *(stack + i)); 110 } 111}
###質問したいこと
<push>停止と書いたところがあるのですが、なぜこのやり方だと動作が停止してしまうのか。
配列stackの0番目以降に(stack[1]やstack[2]など)にdataを入れるためには、*(stack+(top++))ではなぜだめで、stack[0]にしか格納されないのか。
<pop>pushと同様にどのような書き方をすれば値を取り出せるのか。
<print_stack>ここに関しては理解ができなかったので、自分が思うままにコードを書いてしまったので、間違っているところを指摘、修正案をお願いいたします。
###その他
main関数をいじるのでは無く、自作関数を書き換えろという意図があります。
まだまだ途中な上、多くの質問をしてしまいとても大変だと思われますが、どうか返答のほどよろしくお願いいたします。厚かましいとは思いますが、しっかりここの分野も理解したいのでどうか詳しく解説をしていただけると助かります。どうかよろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/30 10:16