J Wu J Wu - 3 months ago 7
C Question

Compiling error when calling a function pointer in C

I am writing a program that calls a function pointer that points to a function from another file. When I compiled the program, I received an error message from the compiler saying that there was an expected expression.
Here is one of the four errors produced:

error: expected expression
(*get_num)(int *, int *);


The compiler says that the expression is expected between the
(
and the
int
.
The same error is shown for each of the other three function pointer calls.
Am I calling the the function pointer correctly?

#include <stdio.h>

int getnum(int items[], int *amount);
int sortnum(int items[], int amount);
int printnum(int items[], int amount);
int searchnum(int items[], int amount);

int (*get_num)(int *, int *);
int (*sort_num)(int *, int);
int (*print_num)(int *, int);
int (*search_num)(int *, int);

int main()
{
int items[maxitem];
int amount;

get_num = getnum;
sort_num = sortnum;
print_num = printnum;
search_num = searchnum;

(*get_num)(int *, int *);
(*sort_num)(int, int);
(*print_num)(int, int);
(*search_num)(int, int);
}

Answer

When calling a function, you need to provide suitable values as arguments. The call

(*get_num)(int *, int *);

doen't do that.

Use

(*get_num)(items, &amount);

or the more readable:

get_num(items, &amount);

Make similar changes for the other calls.

(*sort_num)(items, amount);
(*print_num)(items, amount);
(*search_num)(items, amount);