I want to write a program with following signature where the function will be applied to all the elements of the array in c.
void map(unsigned(*function_name)(unsigned),
size_t funct_length,
arr_name[funct_length]);
Everything is unsigned.
CodePudding user response:
There are a few blanks on your question, but the following code provides you with a starting point. Some issues:
(*function_name)(unsigned)
is a pointer function, the other parameters are the array size and a pointer to the array, I produced two invented functions, map_add_point
and map_remove_point
, so each function will be applied to all the elements of the array.
void map(unsigned (*function_name)(unsigned), size_t funct_length, unsigned arr_name[]);
unsigned map_add_point(unsigned);
unsigned map_remove_point(unsigned);
int main()
{
unsigned points_a[] = {1,2,3};
unsigned points_b[] = {1,2};
map(map_add_point, sizeof(points_a)/sizeof(unsigned), points_a);
map(map_remove_point, sizeof(points_a)/sizeof(unsigned), points_b);
return 0;
}
void map(unsigned (*funct_length)(unsigned), size_t length, unsigned arr_name[])
{
size_t n;
for (n = 0; n < length; n )
{
(*funct_length) (arr_name[n]);
}
}
unsigned map_add_point(unsigned point)
{
printf("\nPoint to add: %d", point);
return 0;
}
unsigned map_remove_point(unsigned point)
{
printf("\nPoint to remove: %d", point);
return 0;
}
CodePudding user response:
Minimalistic:
void map(unsigned(*function_name)(unsigned), size_t funct_length, unsigned arr_name[funct_length])
{
while(funct_length--)
{
*arr_name = function_name(*arr_name);
arr_name ;
}
}