-1

I am making a trivia game and want to run random questions that I have in functions. I have created this code as a test these are not the actual functions I would run:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int N = 3;
void (*func_ptr[3]) = { moreInformation, startofgame, level1}; [rand() % N]();

but every time I run it I get an error saying I have to put an identifier in the last pair of parentheses. Is there a different way to do this or what should I put as an identifier in the parentheses.

bobbyjoe
  • 17
  • 1
  • 6
  • 1
    You array isn't an array of pointer to functions, it's an array of pointer to `void`. You also can't have generic statements outside of function scope. And you need to specify the array to index (which probably is what the error you mention is about). So there's plenty of problems with the code you show. – Some programmer dude Mar 02 '19 at 19:27
  • Possible duplicate of [How can I use an array of function pointers?](https://stackoverflow.com/questions/252748/how-can-i-use-an-array-of-function-pointers) – Weather Vane Mar 02 '19 at 19:29
  • @WeatherVane Yeah that is where I got this from but I am wondering if there is a different and better way to do this. – bobbyjoe Mar 02 '19 at 19:33
  • Possible duplicate of [How can I use an array of function pointers?](https://stackoverflow.com/questions/252748/how-can-i-use-an-array-of-function-pointers) – user24343 Mar 02 '19 at 20:57

1 Answers1

1

I don't know whether this qualifies as "different and better" but it is a simple and straight-forward working example.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void question1(void) {
    puts("Question 1");
}

void question2(void) {
    puts("Question 2");
}

void question3(void) {
    puts("Question 3");
}

void (*function_ptr[3])(void) = {question1, question2, question3 };

int main(void)
{
    srand((unsigned)time(NULL));
    (*function_ptr[rand() % 3])();
    return 0;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56