“error: invalid use of void expression” when using

2019-08-19 03:48发布

问题:

This question already has an answer here:

  • How do you pass a function as a parameter in C? 7 answers

I get this error when trying to compile: `error: invalid use of void expression

I get this error at the penultimate line: queueDump(f, q, printToken(f, e)); and I don't understand why. I'm trying to code the function printToken that prints the token pointed by e

void queueDump(FILE *f, Queue *q, void(*dumpfunction)(FILE *f, void *e)) {
    fprintf(f, "(%d) --  ", q->size);
    for (InternalQueue *c=q->head; c != NULL; c = c->next)
        dumpfunction(f, c->value);
}

void printToken(FILE *f, void *e) {
    Queue *q;
    if (!f) {
        printf("Erreur d'ouverture du fichier\n");
        exit(1);
    }
    fprintf(f, "Infix : ");
    queueDump(f, q, printToken(f, e));
    fclose(f);
}

回答1:

Your queueDump function expects a pointer to a function while you pass the result of the execution to it.

printToken(f, e) executes function printToken with parameters f and e. Instead of this you should pass 3 parameters to queueDump - printToken, f, e; queueDump will use these parameters to perform the actual execution.

(in your specific case FILE *f and c->value are used as parameters to prinToken so no need to pass additional params)