ウゴレンの答え(および少しOT)に追加するだけで、比較的興味深いアプローチは.stack
、デフォルトで空に初期化されるセクションで仕様空間を拡張することだと思います(あなたの例のように)。
これは、予想される計算の中間段階を記述するために使用できます (ある時点で実際の状態を保存/復元します)。
実装するには、次のような非常に単純なコードを使用します
ファイル stack.h:
#ifndef STACK
#define STACK
#include <stdio.h>
/* here should be implemented the constraint about 32 bits words... */
typedef int word;
typedef struct { int top; word* mem; int allocated; } stack;
typedef stack* stackp;
stackp new_stack();
void free_stack(stackp);
void push(stackp s, word w);
word pop(stackp p);
/* extension */
stackp read(FILE*);
void write(stackp, FILE*);
#endif
ファイル stack.c:
/* example implementation, use - arbitrary - chunks of 2^N */
#include <stdlib.h>
#include "stack.h"
/* blocks are 256 words */
#define N (1 << 8)
stackp new_stack() {
stackp s = calloc(1, sizeof(stack));
s->mem = malloc((s->allocated = N) * sizeof(word));
return s;
}
void free_stack(stackp s) {
free(s->mem);
free(s);
}
void push(stackp s, int w) {
if (s->top == s->allocated) {
s->allocated += N;
s->mem = realloc(s->mem, s->allocated * sizeof(word));
}
s->mem[s->top++] = w;
}
word pop(stackp s) {
if (s->top == 0) { /* exception */ }
return s->mem[--(s->top)];
}
ファイル main.c:
#include "stack.h"
int main() {
stackp s = new_stack();
word X = 3;
word Y = 5;
push(s, X);
push(s, Y);
word Z = pop(s) + pop(s);
printf("Z=%d\n", Z);
free_stack(s);
}
ファイルメイクファイル:
main: main.c stack.c
構築する:
make
テストする:
./main
Z=8
いくつかの違いに注目する価値があります WRT ugoren の回答:データの隠蔽、実装の貴重な部分を強調し、実際の関数に関する詳細を別のファイルに保持します。そこでは、たとえば最大スタック サイズ (実際には強制されていません)、エラー処理など、多くの詳細を追加できます...
edit : プッシュされた単語の「アドレス」を取得する
word push(stackp s, int w) {
if (s->top == s->allocated) {
s->allocated += N;
s->mem = realloc(s->mem, s->allocated * sizeof(word));
}
s->mem[s->top] = w;
return s->top++;
}