See these examples:
Case 1: using a pointer vector and size
Declare the vector thus:
double (*ptrs[])(double) = {f00, f01};
And in function so:
void Teste1(int,double (*[])(double));
note that you can already list the function names in the statement, if it is something constant.
a full test
#include <stdio.h>
#include <stdlib.h>
double f00(double);
double f01(double);
void Teste1(int,double (*[])(double));
int main(void)
{
double (*ptrs[])(double) = {f00, f01};
Teste1(2, ptrs);
return 0;
}
double f00(double x)
{
printf("F0(%.1f) chamada\n", x);
return 42.0;
}
double f01(double x)
{
printf("F1(%.1f) chamada\n", x);
return 42.1;
}
void Teste1(int tam, double (*F[])(double))
{
printf("%d funcoes a chamar\n", tam);
for (int i = 0; i < tam; i += 1)
printf("Funcao %d retornou %.1f\n", i, F[i]((double)i));
}
exit
2 funcoes a chamar
F0(0.0) chamada
Funcao 0 retornou 42.0
F1(1.0) chamada
Funcao 1 retornou 42.1
Case 2: a pointer vector, NULL-terminated
It can be useful when it will always process all the records, in order, as a batch.
It’s simpler to use one typedef
, something like that:
typedef double (*Fd_d)(double);
And declare the function with him
void Teste2(Fd_d*);`
In this case you have to mount the vector, as the system does with main()
and the vector of arguments:
Fd_d* vetor = (Fd_d*)malloc(3 * sizeof(Fd_d));
vetor[0] = f00;
vetor[1] = f01;
vetor[2] = NULL;
Teste2(vetor);
A complete example
#include <stdio.h>
#include <stdlib.h>
double f00(double);
double f01(double);
typedef double (*Fd_d)(double);
void Teste2(Fd_d*);
int main(void)
{
printf("\nUsando vetor de ponteiros\n\n");
Fd_d* vetor = (Fd_d*)malloc(3 * sizeof(Fd_d));
vetor[0] = f00;
vetor[1] = f01;
vetor[2] = NULL;
Teste2(vetor);
return 0;
}
double f00(double x)
{
printf("F0(%.1f) chamada\n", x);
return 42.0;
}
double f01(double x)
{
printf("F1(%.1f) chamada\n", x);
return 42.1;
}
void Teste2(Fd_d* vetor)
{
int i = 0;
while (vetor[i] != NULL)
printf("Funcao %d retornou %.1f\n", i, vetor[i]((double)i)), i ++;
}
Departure from the example
Usando vetor de ponteiros
F0(0.0) chamada
Funcao 0 retornou 42.0
F1(1.0) chamada
Funcao 1 retornou 42.1
Maybe this other question will help you: https://answall.com/questions/2983/como-passar-uma-fun%C3%A7%C3%a3o-como-par%C3%a2metro-em-c? Rq=1
– epx
In the case of this answer he is passing a reference to each function. If I wanted to receive a reference, for example to my function
f00
, I would have a header withdouble(*f) (double x)
as parameter. But in case I want to receive a list with these references, and not just once.– João Verçosa
But I came up with an idea and then I’m gonna test it:
double* (*f) (double x)
.– João Verçosa
If the idea you had was to make a typedef will probably work.
– Vander Santos