I have this struct:
typedef struct {
void (*func)(instruction);
union {
double db;
char ch;
};
} instruction;
Within my source file, I have an array of these instructions. My question is, how would I loop through that array and execute each struct's function?
I thought I knew how to do this, but the fact that the instruction function has a parameter that is an instruction seems to cause problems. As such, this does not work:
int i;
for (i = 0; i <= instr_count; i++) {
(*instr[i].func) (instr[i]);
}
instr being the array of instructions.
Here is the function that populates the array. The array itself is declared at the top of the file.
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);
}
As a quick explanation, this code takes a file of "intermediate code", determines the instruction, and creates an instruction struct for each that holds the proper function pointer.
Running the code gives me this runtime error:
"Unhandled exception at 0x00000000 in Interpreter.exe: 0xC0000005: Access violation." (Compiled using VS 2010).