How to declare an array that is received like an parameter in a function that also receive a pointer to a function in C and that function is using the values from the array? The function that use the values from the array doesn't receive a parameter. It's something like:
int find_array(void)
and the function that receive this function like parameter also receive the array. I think that declaration should look something like:
int function ( int (*pmin)(void), int* array )
How the function find_array
knows that it should work with the array received like parameter? How to declare this array?
CodePudding user response:
int function should receive just 2 parameters, a pointer to function find_array and the array. I should also to find a way to declare the size of the array
It had to be extended to three parameters in order to give the size of the array:
#include <stdio.h>
// simple function working on an array
int find_minimum(int *array, int n) {
int minimum = array[0];
for (int i = 1; i < n; i ) {
if (array[i] < minimum) {
minimum = array[i];
}
}
return minimum;
}
// function receiving an array and a function to process it
int function(int (*pmin)(int *array, int n), int *array, int n) {
return pmin(array, n);
}
int main() {
int array[] = {1, 2, -3, 4, 5};
int min = function(find_minimum, array, sizeof array / sizeof(int));
printf("minimum: %d\n", min);
return 0;
}
Looks good:
$ gcc -Wall -Werror array.c
$ ./a.out
minimum: -3
$
Regarding the parameter for the function to be give as parameter you might want to use ellipsis for a variable amount of parameters, see https://en.wikipedia.org/wiki/Ellipsis_(computer_programming).