im currently training myself in passing functions as parameters, but i cant get my logic to work. Hope one of you can help!
I have a function called 'square' which takes an int and returns the square of it.
Then i have another function called 'map', which takes a list of numbers and the square function as input, and i'd like to square each of these numbers in the map function.
I declare my pointer to square function in main, but since it takes an int as parameter, it just squares that initial integer for all the numbers in my list. How do i assign my function to a variable, in a way such as when i pass it to the map function, i can change what int gets passed to the square function
int b = 1; //Global variable
int square (int x) {
return x*x;
}
int map (struct node *head, int x) {
int z = head->data; //this variable is what i want squared.
// If i call x here itll use the b variable and square that.
//changing b doesnt work either since it takes the value that b had when map function was called
if (head->next == NULL) {
return 0;
}
else {
printf("Value: %d", z)
map(head->next, x);
}
return 0;
}
int main(void) {
int (*sf)(int);
sf = square; //Assigning the square function to the sf variable
int x =(*sf)(b); //here is the problem, b is the variable thatll get squared every time my function runs
map(head,x); //passing x (square function) and head of a linked list