c - 循环遍历函数指针数组

标签 c function pointers

我有这个结构:

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);
}

作为快速解释,此代码采用“中间代码”文件,确定指令,并为每个包含正确函数指针的指令结构创建一个指令结构。

运行代码给我这个运行时错误:

"Unhandled exception at 0x00000000 in Interpreter.exe: 0xC0000005: Access violation." (Compiled using VS 2010).

最佳答案

根据 instrinstruction 数组还是 instruction *,您需要其中一个

instr[i].func(&instr[i]);

instr[i]->func(instr[i]);

我怀疑你想要第一个(指令数组),因为你所拥有的将为此进行编译(在大多数编译器上都会发出警告);你只会得到函数中参数的垃圾。

但是,您遇到的异常表明这不是您的问题 - 您的数组中可能有一 strip 有 NULL func 指针的指令。

编辑

看起来您正在犯经典的 while(!feof(input)) 错误 - 每当您看到此错误时,它几乎总是错误的。

问题是,在您读取输入的最后一行后,feof 仍将返回 false - 在您尝试读取 PAST 输入的末尾之前,它不会返回 true an 收到 EOF 结果。因此,您将在输入代码结束后获得一个额外的循环迭代,并带有一个空行,这可能会导致您看到的崩溃。

您可能想要的是类似 while (!(str = get_next_string()))while (!(str = fgets(buffer, sizeof(buffer), datafile) ))

关于c - 循环遍历函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388591/

相关文章:

c - 在声明结构对象之前是否可以选择使用 struct 关键字?

php - call_user_func_array() args 以字符串作为键来匹配函数参数名称

php - 替换字符串中子字符串每次出现但最后一次出现的有效/简单方法(str_replace_except_last)?

c - 数组名是C语言中的指针吗?

c - 是否需要 Cast to void**?

float 与 C 中的值的比较

c - 目录和文件的递归列表 C

scala - def 是否被视为 Scala 中的闭包?

c++ - 虚拟继承中的 vptr 数

c++ - 将指针地址更改为另一个对象