ft_list_foreach — Apply Function to List
Allowed functions: none
Write a function that takes a list and a function pointer, and applies this function to each element of the list.
void ft_list_foreach(t_list *begin_list, void (*f)(void *));
The function pointed to by f will be used as follows:
(*f)(list_ptr->data);
Solution
Download ft_list_foreach.c#include "ft_list.h"
void ft_list_foreach(t_list *begin_list, void (*f)(void *)) {
while (begin_list) {
(*f)(begin_list->data);
begin_list = begin_list->next;
}
}
How It Works
Goal: Apply a given function to the data of every element in a linked list.
Approach: Traverse the list node by node, calling the function pointer on each node's data.
Step by step:
- Loop while
begin_listis not NULL. - Call
(*f)(begin_list->data)to apply the function to the current node's data. - Advance to the next node with
begin_list = begin_list->next.
Key concept: Function pointers — passing a function as a parameter and invoking it with (*f)(arg) syntax.