私はこの構造体を持っています:
typedef struct {
void (*func)(instruction);
union {
double db;
char ch;
};
} instruction;
ソースファイル内に、これらの命令の配列があります。私の質問は、その配列をループして各構造体の関数を実行するにはどうすればよいですか?
やり方は知っていると思いましたが、命令関数に命令というパラメータがあるので問題が発生しているようです。そのため、これは機能しません。
int i;
for (i = 0; i <= instr_count; i++) {
(*instr[i].func) (instr[i]);
}
instrは命令の配列です。
配列にデータを取り込む関数は次のとおりです。配列自体はファイルの先頭で宣言されます。
void read_instructions()
{
char* str;
char *instruct;
int n;
char c;
instruction next = {0};
while (!feof(datafile)) {
// Fetch the next string
// if (push or pop), get the next argument
// create instructiwn and add to instruction array
str = get_next_string();
instruct = strtok (str, " ");
if (strncmp (instruct, "P", 1) == 0) {
char *arg = strtok (NULL, " ");
if (strncmp (str, "PUSH", 4) == 0) {
next.func = pushFunc;
}
else {
next.func = popFunc;
}
n = arg[0];
if (n > 64 || n < 71)
next.ch = n;
else {
double n;
scanf ("%lf", arg, n);
next.db = n;
}
instr[instr_count] = next;
instr_count++;
}
else {
c = instruct[0];
switch (c) {
case 'A' :
next.func = addFunc;
break;
case 'S' :
next.func = subFunc;
break;
case 'M' :
next.func = multFunc;
break;
case 'D' :
next.func = divFunc;
break;
default :
break;
}
instr[instr_count] = next;
instr_count++;
}
}
fclose (datafile);
}
簡単に説明すると、このコードは「中間コード」のファイルを取得し、命令を決定し、適切な関数ポインターを保持するそれぞれの命令構造体を作成します。
コードを実行すると、次のランタイムエラーが発生します。
Interpreter.exeの0x00000000で未処理の例外:0xC0000005:アクセス違反です。(VS 2010を使用してコンパイル)。